onStop being called after onDestroy? onStop being called after onDestroy? android android

onStop being called after onDestroy?


The reason is unclear, but, it is getting more and more attention recently. And it happens in both onResume/onPause and onStart/onStop pairs to call register/unregister. About those lifeCycle checks, make sure you have on Instance of the activity with hashCode() or something. Anyway, to fix the issue the best practice is to wrap register/unregister calls in try/catch block:

private void registerBroadcastReceiver() {    try {        appUpdateReceiver = new AppUpdateReceiver();        registerReceiver(appUpdateReceiver, appUpdateIntentFilter);    } catch (IllegalArgumentException e) {        // already registered    }}private void unregisterBroadcastReceiver() {    try {        unregisterReceiver(appUpdateReceiver);    } catch (IllegalArgumentException e) {        // already unregistered    }}


I am not entirely sure why that happens in the first place, but I've encountered something similar on one of the Xiaomi devices that did not happen on any of the emulators (or my device), but happened on somebody else's phone. onStop() was called 5 seconds after the app was moved to background, but onPause() was called immediately. More weird issue, if in between these 5 seconds, I open the app from task manager, onStart() was called. (Notice the 2 onStart() calls but not a singular onStop() call.) I think it would have been possible if the activity was destroyed, onDestroy() would be called before onStop(). As an alternative, you might try to move the receiver registration calls to onResume() and onPause() instead of onStart() and onStop().

Second: I don't exactly use lifecycle of the activity when it comes to checking resumed or paused state, but I'd suggest overriding all of those methods (onPause, onResume etc...), storing the state on boolean variables and logging the state while checking the actual calls. Maybe that will result in a different state since this is a pretty unusual check.

If it does not happen on other activities, in that activity, maybe something is posting so many callbacks to the main message looper that prevents onStop() from getting called in the first place because of the overflow, causing this exception to happen. These are only assumptions, of course, but I'd be grateful if they helped in a way.