简体   繁体   中英

Android Bluetooth Pairing: How to make sure to get bluetooth pairing request in the front dialog instead of a notification?

另外,如果我收到通知,有没有办法以编程方式单击它并将配对请求放在前面?

for reference to explain why and what, please have a look here: Bluetooth pairing request on notification bar?

The solution is quite easy if you know it and if it fits into your application:

private void feintBluetoothDeviceDiscovery() {
    BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
    btAdapter.startDiscovery();
    btAdapter.cancelDiscovery();
}

Call feintBluetoothDeviceDiscovery() before you try to pair or connect your bluetooth device. The popup should appear in the front.

We also had this issue in our automated tests. A pairing request only showing as notifications are a pain there. Thank to a colleague for sharing the code.

Use uuid cache followed by uuid in the following order.

private void SOKETHAZIRLA() {

    Log.i("ZZZZZZ", String.valueOf(btDevice.getBondState()));


    Thread connectThread = new Thread(() -> {
        try {
            if (btDevice != null) {

                Log.i("BTDevice", "Cihaz Name: " + btDevice.getName());
                Log.i("BTDevice", "Cihaz UUID: " + btDevice.getUuids()[0].getUuid());
                mbtSocket = btDevice.createRfcommSocketToServiceRecord(btDevice.getUuids()[0].getUuid());
                Log.d("BTDevice", "1. connect.");
                mbtSocket.connect();

            } else {
                Log.d("BTDevice", "Device is null.");
            }
        } catch (Exception ex) {
            try {

                mBluetoothAdapter.startDiscovery();

                if (btDevice != null) {
                    mbtSocket = btDevice.createRfcommSocketToServiceRecord(uuid);
                    Log.d("BTDevice", "2. connect.");
                    mbtSocket.connect();
                }

            } catch (IOException e) {
                e.printStackTrace();
                try {
                    mbtSocket.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }

                runOnUiThread(socketErrorRunnable);
                mbtSocket = null;
            }
        } finally {
            runOnUiThread(this::finish);
        }
    });
    connectThread.start();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM