How to solve the BluetoothGatt : android.os.DeadObjectException error happened in Android?

前端 未结 4 2002
北恋
北恋 2021-02-13 18:07

I following the page Bluetooth Low Energy for developing in Android 4.3 for Bluetooth Low Energy .

I already can turn on the Bluetooth

相关标签:
4条回答
  • 2021-02-13 18:27

    My workaround to the problem was to delay the reconnection:

    private void connectGatt(final String address) {
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                bluetoothGatt = bluetoothManager.getAdapter().getRemoteDevice(address).connectGatt(context, true, bluetoothGattCallback);
            }
        }, 500);
    }
    
    0 讨论(0)
  • 2021-02-13 18:32

    I solved this by disconnecting, closing the Gatt and stopping the service and then restart it again:

                mBluetoothLeService.disconnect();
                mBluetoothLeService.close();
                mBluetoothLeService.stopSelf();
                connectBleservice();
    
    0 讨论(0)
  • 2021-02-13 18:39

    This problem is very tricky to solve but seems to have to do with some sort of race condition in the android bluetooth stack. Doug's answer of catching Exception e and then checking if its a dead object did not work when I tried. I did notice that when I call

    bluetoothGatt.connect()
    

    a return value of false can indicate a dead object exception.

    0 讨论(0)
  • 2021-02-13 18:46

    The dreaded DeadObjectException is an unfortunate reality of Android BLE and after 6 months working with the API I never figured out what it is or how to prevent it. It can happen in other circumstances than what you're describing. For example for me it usually happens when calling BluetoothDevice#getName() after discovery.

    Anyway, the best thing you can do is wrap the problem call with:

    try
    {
        // your DeadObjectException inducing code.
    }
    catch(Exception e)
    {
        // Can't actually catch the DeadObjectException itself for some reason...*shrug*.
        if( e instanceof DeadObjectException )
        {
            // notify user through a dialog or something that they should either restart bluetooth or their phone.
            // another option is to reset the stack programmatically.
        }
        else
        {
            // your choice of whether to rethrow it or treat it the same as DeadObjectException.
        }
    }
    

    Note that the Bluetooth stack can also throw random NullPointerExceptions that can really only be dealt with the same way - either telling your user how to reset phone or bluetooth, or trying to programmatically restart bluetooth.

    0 讨论(0)
提交回复
热议问题