如何知道蓝牙配对何时完成

时间:2015-08-08 00:17:02

标签: android bluetooth

我希望在完成配对时通过蓝牙收听传入消息。在配对完成之前我不能打电话听(可以吗?),我不知道它什么时候完成。

我尝试了很多方法在两个设备之间配对,如下所示:

   private void pairDevice() {
    try {
        BluetoothDevice device = bluetooth.getRemoteDevice(address);
        Log.d("pairDevice()", "Start Pairing...");
        Method m = device.getClass().getMethod("createBond", (Class[]) null);
        m.invoke(device, (Object[]) null);
        Log.d("pairDevice()", "Pairing finished.");
    } catch (Exception e) {
        Log.e("pairDevice()", e.getMessage());
    }
}

这一个很好但是它会打开一个弹出窗口来接受配对,并且在接受弹出对话框之前调用Log.d("pairDevice()", "Pairing finished.");并且我只有在配对完全完成并且设备现在才需要做事情配对。这是我收听消息的代码:

public void run() {
    final int BUFFER_SIZE = 1024;
    byte[] buffer = new byte[BUFFER_SIZE];
    int bytes = 0;
    int b = BUFFER_SIZE;
    while (true) {
        try {
            bytes = inStream.read(buffer, bytes, BUFFER_SIZE - bytes);
            textview.setText(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

这是我发送邮件的代码(得分):

  private void init() throws IOException {
    if (bluetooth != null) {
        if (bluetooth.isEnabled()) {
            Set<BluetoothDevice> bondedDevices = bluetooth.getBondedDevices();
            if (bondedDevices.size() > 0) {
                ParcelUuid[] uuids = device.getUuids();
                BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
                socket.connect();
                outputStream = socket.getOutputStream();
                inStream = socket.getInputStream();
                write(score);
            }
            Log.e("error", "No appropriate paired devices.");
        } else {
            Log.e("error", "Bluetooth is disabled.");
        }
    }
}

public void write(String s) throws IOException {
    outputStream.write(s.getBytes());
}

我尝试在没有用户许可的情况下将两台设备配对,就像在这个答案中一样 - here - 但它也要求权限我不知道为什么......所以实际上我并不认为我需要未经允许配对我只需要在接受弹出窗口时做一些事情。可能吗?感谢。

0 个答案:

没有答案
相关问题