java - 安卓蓝牙

标签 java android bluetooth

<分区>

我一直在努力通过 android 建立蓝牙连接。

我尝试构建它几个星期,但只有一半的代码可以正常工作。

工作的部分是:

  1. 打开/关闭蓝牙;

  2. 查找配对设备;

  3. 扫描可用设备。

谁能给我发一份源代码,其中包含通过 Bluetoothsocket 连接的部分?

这对我很有帮助

最佳答案

通过蓝牙套接字连接的异步类

 UUID SERIAL_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");

BluetoothSocket socket = null; 

class UserInterface extends Thread {
    BluetoothDevice bdDevice;
    public UserInterface() {
        bdDevice = your pair device;

    }

    @Override
    public void run() {
        Looper.prepare();
        try {

            BluetoothDevice device = bluetoothAdapter.getRemoteDevice(bdDevice.getAddress());

            if (socket != null && socket.isConnected()) {
                is1.close();
                os1.close();
                socket.close();

            }
            try {
                socket = device.createInsecureRfcommSocketToServiceRecord(SERIAL_UUID);
            } catch (Exception e) {
                Log.e("", "Error creating socket");
            }
            if (bluetoothAdapter.isDiscovering()) {
                bluetoothAdapter.cancelDiscovery();
            }


            try {
                socket.connect();
                Log.e("", "Connected Rfcomm");

            } catch (IOException e) {
                Log.e("", e.getMessage());
                try {
                    Log.e("", "trying fallback...");

                    socket = device.createInsecureRfcommSocketToServiceRecord(SERIAL_UUID);
                    socket.connect();
                    Log.e("", "Connected serial UDID");

                } catch (Exception e2) {
                    Log.e("", "Couldn't establish Bluetooth connection!");
                }
            }


            if (socket.isConnected()) {
                dismissProgressDialog();
               //code after socket connect

            } else {
                dismissProgressDialog();
                showProgressDialogToast("Please restart polaroid bluetooth");
                closeSocket();
                Log.i("TAG", "Socket Disconnected");
            }

            Log.i("Log", "Removed" + bdDevice.getName());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            Log.i("Log", "Under Catch of thread");
            e.printStackTrace();
            dismissProgressDialog();
        }
    }
}

像这样使用线程类

UserInterface userInterface = new UserInterface();
userInterface.start();

关于java - 安卓蓝牙,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34011610/

相关文章:

java - 当更多的对象意味着更多的实现时间时,为什么人们鼓励在 java 中使用更多的类?

android - 使用 AGConnectServicesConfig 获取 appId 失败

iPhone - 通过蓝牙发送图像和文本的错误

android - 使用 3.5 毫米音频端口和微型 USB 进行串行通信

java - 如何从 Spring Boot jar 构建 Docker 镜像

java - Docker 如何从容器内的Web服务连接到MongoDB

java - 获取枚举的字符串值

android - 哪个gradle任务会构建AndroidTest。* apk,并且不会执行任何其他操作

java - 从 Android 上的另一个类调用方法

android - 蓝牙查找设备落下程序