4

I have an issue about unregisterReceiver function. In my service, I have a function to register a mGattUpdateReceiver as follows

if (bluetoothAdapter.isEnabled()) {
  Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
  bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
  registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
}

And I release it in onDestroy function

public void onDestroy() {
    if (mGattUpdateReceiver != null) {
       unregisterReceiver(mGattUpdateReceiver);
    }
    if (mServiceConnection != null) {
       unbindService(mServiceConnection);
    }
}

The above process worked well when my bluetooth is turn on. However, if the bluetooth is turn off, the register function does not pass. Hence, I got the error as

Caused by: java.lang.IllegalArgumentException: Receiver not registered

Hence, I need to know the receiver (mGattUpdateReceiver) is registered or not. How to check it in Android? Thank all

Jame
  • 3,746
  • 6
  • 52
  • 101
  • This question was already asked [here](http://stackoverflow.com/questions/2682043/how-to-check-if-receiver-is-registered-in-android) – MatPag Jan 02 '17 at 12:13
  • 1
    Do you tried it? I tried these method but it does not work. Could you recommend to me which one is good – Jame Jan 02 '17 at 12:14
  • 1
    well a solution that I found in this link http://stackoverflow.com/questions/20329949/check-if-the-broadcstreceiver-is-registered , is to put your code of onDestroy() method inside a try/catch block. – Vivek Mishra Jan 02 '17 at 12:16
  • @user8430 it is better to register receiver anyways, if bluetooth is not enabled you simply will not receive callback, otherwise add flag if it regestered or not – Lebedevsd Jan 02 '17 at 12:21
  • Flag is not good solution. I think about this before. @VivekMishra: Thanks. The try catch is work. Do you have any other better solution? Because try catch as `try { unregisterReceiver(mGattUpdateReceiver); } catch (IllegalArgumentException e) { e.printStackTrace(); }` print the log error – Jame Jan 02 '17 at 12:24
  • 1
    you usually don't have to do anything if it enters catch block. For another solution you can force user to turn on bluetooth if that is really important for your app. – Vivek Mishra Jan 02 '17 at 12:27

0 Answers0