Search code examples
androidondestroy

Can we have blocking waits in onDestroy()?


I have a BroadcastReceiver which listens for an intent in onDestroy() callback. And there is a blocking while which goes on till bluetooth discoverability is switched off. Once discoverability is off, the changeModeReceiver will call its onReceive() and set destroy_ok to true, and hence breaking out of the while loop. But, this is not giving desired results.

  • Toast message, "In onDestroy()" is not getting printed
  • "In onDestroy()" is getting printed in the logcat
  • The bluetooth is still switched on

The code is as follows.

boolean destroy_ok = false;

protected void onDestroy(){ 

    System.out.println("In onDestroy()");

    Toast.makeText(getApplicationContext(), "In onDestroy()", Toast.LENGTH_LONG).show();

    BroadcastReceiver changeModeReceiver  = new BroadcastReceiver(){
        public void onReceive(Context context, Intent intent){
            String mode = intent.getStringExtra(BluetoothAdapter.EXTRA_SCAN_MODE);
            if (mode.equals(BluetoothAdapter.SCAN_MODE_NONE))
                destroy_ok = true;
        }
    };

    IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
    registerReceiver (changeModeReceiver, filter);

    Intent discoverableIntent = new
    Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
    discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,1);
    startActivity(discoverableIntent);

    while (!destroy_ok){}

    unregisterReceiver(changeModeReceiver);

    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();

    if (adapter.isEnabled())
        adapter.disable();

    System.out.println("Leaving onDestroy()");

    super.onDestroy();

}

Solution

  • The onDestroy method (as well as all other activity lifecycle methods, view callback methods, etc.) is called on the application's main UI thread, so no, you shouldn't block for a significant period of time when called. Doing so will likely result in lag, and may even spawn an ANR (application not responding) error if you block for more than 5-10 seconds.