有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

安卓上的java蓝牙

我一直在努力通过安卓建立蓝牙连接

我尝试了几周的时间来构建它,但我的代码只有一半是有效的

正在工作的部分是:

  1. 打开/关闭蓝牙

  2. 找到配对设备

  3. 扫描可用设备

有人可以通过Bluetoothsocket向我发送包含连接部分的源代码吗

这对我真的很有帮助


共 (2) 个答案

  1. # 1 楼答案

    用于通过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();
    
  2. # 2 楼答案

    对于Android手机,蓝牙插座将在蓝牙开启后监听端口。您应该创建一个蓝牙客户端以连接到蓝牙服务器