Исключение Ble GattServer DeadObject при включении / выключении Bluetooth - PullRequest
0 голосов
/ 22 октября 2018

Мой gattServer объявляет некоторые данные с помощью сопряженного устройства Bluetooth, и я запускаю этот gattServer с сервисом. Все в порядке с состоянием Bluetooth, но я выключил Bluetooth и снова включил исключение этой строки

 sGattServer.notifyCharacteristicChanged(device, getCharacteristic(Constants.NOTIFICATION_SOURCE), false);

ЭтоСпособ подключения

  BluetoothAdapter bleAdapter = ((BluetoothManager) context.getSystemService(BLUETOOTH_SERVICE)).getAdapter();
    final Set<BluetoothDevice> pairedDevices = bleAdapter.getBondedDevices();
    for (BluetoothDevice d : pairedDevices) {

        d.connectGatt(context, true, new BluetoothGattCallback() {

            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onConnectionStateChange(BluetoothGatt
                                                        gatt, int status, int newState) {
                switch (newState) {
                    case BluetoothProfile.STATE_CONNECTED:


                        gatt.getServices();
                        break;
                    case BluetoothProfile.STATE_DISCONNECTED:


                        if (gatt !=null){
                            gatt.close();
                            gatt.disconnect();
                            gatt.connect();
                        }


                        break;
                }
            }
        });
    }

Застрял след здесь:

10-23 10:04:53.978 27768-27768/E/BluetoothGattServer: android.os.DeadObjectException
    at android.os.BinderProxy.transactNative(Native Method)
    at android.os.BinderProxy.transact(Binder.java:496)
    at android.bluetooth.IBluetoothGatt$Stub$Proxy.sendNotification(IBluetoothGatt.java:1482)
    at android.bluetooth.BluetoothGattServer.notifyCharacteristicChanged(BluetoothGattServer.java:539)

1 Ответ

0 голосов
/ 02 августа 2019

Когда Bluetooth выключен, Android перезапускает стек Bluetooth, чтобы очистить его состояние.Вроде как треск грецкого ореха с кувалдой 40 фунтов.См. Logcat

2019-08-02 11:56:29.274 10736-10736/? D/BluetoothAdapterService: onDestroy()
2019-08-02 11:56:29.281 10736-10736/? I/BluetoothAdapterService: Force exit to cleanup internal state in Bluetooth stack

В вашей службе GattServer вам необходимо воссоздать объект BluetoothGattServer при включении Bluetooth.

Вы не отображали код изваш сервис, в котором проблема, но вам нужно будет сделать что-то вроде следующего.Создайте метод createServerGattService , который определяет UUID службы и характеристики вашей службы сервера GATT, а затем регистрирует его в стеке BLE.У вас уже есть это, потому что вы говорите, что сервер GATT работает нормально, пока вы не выключите адаптер Bluetooth и не включите его.

Добавьте приемник состояния питания адаптера Bluetooth к вашей службе:

    private BluetoothGattServer gattServer;

    private final BroadcastReceiver m_bluetoothAdapterPowerStateeceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();

            if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
                final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
                        BluetoothAdapter.ERROR);
                switch (state) {
                    case BluetoothAdapter.STATE_OFF:
                        gattServer = null;
                        break;
                    case BluetoothAdapter.STATE_TURNING_OFF:
                        gattServer.close();
                        break;
                    case BluetoothAdapter.STATE_ON:
                        gattServer = createServerGattService();
                        break;
                    case BluetoothAdapter.STATE_TURNING_ON:
                        break;
                }
            }
        }
    };

В onCreate () метод вашего сервиса, зарегистрируйте получателя и создайте экземпляр вашего сервера gatt, если адаптер Bluetooth включен:

    @Override
    public void onCreate() {
        super.onCreate();
        IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(m_bluetoothAdapterPowerStateeceiver, filter);
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter.getState() == BluetoothAdapter.STATE_ON) {
            gattServer = createServerGattService();
        }
    }

В onDestroy () Метод вашего сервиса, удалите получателя и закройте соединение с сервером GATT:

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(m_bluetoothAdapterPowerStateeceiver);
        if(gattServer != null)
            gattServer.close();
    }

Для полноты ответа createServerGattService () должно выглядеть примерно так:

    private BluetoothGattServer createServerGattService() {
        BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
        BluetoothGattServer server = null;
        if(bluetoothManager != null) {
           server = bluetoothManager.openGattServer(this, new BluetoothGattServerCallback() {
                @Override
                public void onConnectionStateChange(BluetoothDevice device, int status, int newState) {
                    super.onConnectionStateChange(device, status, newState);
                }

                @Override
                public void onServiceAdded(int status, BluetoothGattService service) {
                    super.onServiceAdded(status, service);
                }

                @Override
                public void onCharacteristicReadRequest(BluetoothDevice device, int requestId, int offset, BluetoothGattCharacteristic characteristic) {
                    super.onCharacteristicReadRequest(device, requestId, offset, characteristic);
                }

                @Override
                public void onCharacteristicWriteRequest(BluetoothDevice device, int requestId, BluetoothGattCharacteristic characteristic, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) {
                    super.onCharacteristicWriteRequest(device, requestId, characteristic, preparedWrite, responseNeeded, offset, value);
                }

                @Override
                public void onDescriptorReadRequest(BluetoothDevice device, int requestId, int offset, BluetoothGattDescriptor descriptor) {
                    super.onDescriptorReadRequest(device, requestId, offset, descriptor);
                }

                @Override
                public void onDescriptorWriteRequest(BluetoothDevice device, int requestId, BluetoothGattDescriptor descriptor, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) {
                    super.onDescriptorWriteRequest(device, requestId, descriptor, preparedWrite, responseNeeded, offset, value);
                }

                @Override
                public void onExecuteWrite(BluetoothDevice device, int requestId, boolean execute) {
                    super.onExecuteWrite(device, requestId, execute);
                }

                @Override
                public void onNotificationSent(BluetoothDevice device, int status) {
                    super.onNotificationSent(device, status);
                }

                @Override
                public void onMtuChanged(BluetoothDevice device, int mtu) {
                    super.onMtuChanged(device, mtu);
                }

                @Override
                public void onPhyUpdate(BluetoothDevice device, int txPhy, int rxPhy, int status) {
                    super.onPhyUpdate(device, txPhy, rxPhy, status);
                }

                @Override
                public void onPhyRead(BluetoothDevice device, int txPhy, int rxPhy, int status) {
                    super.onPhyRead(device, txPhy, rxPhy, status);
                }
            });
            BluetoothGattService service = new BluetoothGattService(serviceUuid, BluetoothGattService.SERVICE_TYPE_PRIMARY);
            BluetoothGattCharacteristic characteristic1 = new BluetoothGattCharacteristic(
                    characteristic1Uuid,
                    BluetoothGattCharacteristic.PROPERTY_READ,
                    BluetoothGattCharacteristic.PERMISSION_READ);
            service.addCharacteristic(characteristic1);
            server.addService(service);
        }
        return server;
    }

...