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

前端 未结 4 2009
北恋
北恋 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: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.

提交回复
热议问题