How to periodically scan for bluetooth devices on android

后端 未结 4 1265
没有蜡笔的小新
没有蜡笔的小新 2020-12-07 16:35

Hi this may sound as a stupid question.But I was unable to find any answers for this, thus posting here.

I am building an indoor application which continuously scans

4条回答
  •  执笔经年
    2020-12-07 17:17

    As stated in the documentation device discovery is a lofty process that will directly degrade the performance of any bonds you have with other devices.

    Caution: Performing device discovery is a heavy procedure for the Bluetooth adapter and will consume a lot of its resources. Once you have found a device to connect, be certain that you always stop discovery with cancelDiscovery() before attempting a connection. Also, if you already hold a connection with a device, then performing discovery can significantly reduce the bandwidth available for the connection, so you should not perform discovery while connected.

    With this in mind (error handling omitted):

    private final BroadcastReceiver deviceBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
    
                if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                     deviceFound = true;
    
                     adapter.cancelDiscovery();
    
                     //process new device.
    
                     deviceFound = false;
    
                     adapter.startDiscovery();
                }
    }
    
    private final BroadcastReceiver adapterBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
    
                if (BluetoothAdaptor.ACTION_DISCOVERY_FINISHED.equals(action)) {
                     if (deviceFound == false) {
                          adapter.startDiscovery();
                     }
                }
    }
    

提交回复
热议问题