I've encountered a rather strange issue with Activity lifecycle.
Short prequel:
The first symptom that I've found is that it crashed with IllegalArgumentException when I was trying to unregister receiver in onStop after registering it in onStart.
After dumping the full list of active receivers (some reflection magic), I've found that my receiver is not the list. It was either being removed somewhere else by mistake, or it was removed during onDestroy call of Activity where Context is being cleaned (during onDestroy ActivityThread calls ContextImpl#performFinalCleanup, which then calls LoadedApk#removeContextRegistrations).
What is happening?
After adding some more analytics info to the crash, I found out that while the crash is happening in onStop, the Activity is in a pretty weird state - it's isDestroyed() call returns true, it's isFinishing() returns false, and it's getLifecycle().getCurrentState() returns DESTROYED...
Checking normal onStop() (without crash) call shows that the Activity is in this state:
isDestroyed() is false, and getLifecycle().getCurrentState() is CREATED in onStop.
So I drew the conclusion that onStop is being called after onDestroy, which I thought is impossible, but it seems to happen.
And onStop is definitely not being called manually by something else in the app, since this is the stack trace of where the onStop is called from.
com.myapp.TheActivity.onStop (TheActivity.java:217)
android.app.Instrumentation.callActivityOnStop (Instrumentation.java:1474)
android.app.Activity.performStop (Activity.java:8189)
android.app.ActivityThread.callActivityOnStop (ActivityThread.java:4994)
android.app.ActivityThread.performStopActivityInner (ActivityThread.java:4967)
android.app.ActivityThread.handleStopActivity (ActivityThread.java:5047)
android.app.servertransaction.TransactionExecutor.performLifecycleSequence (TransactionExecutor.java:233)
android.app.servertransaction.TransactionExecutor.cycleToPath (TransactionExecutor.java:201)
android.app.servertransaction.TransactionExecutor.executeLifecycleState (TransactionExecutor.java:173)
android.app.servertransaction.TransactionExecutor.execute (TransactionExecutor.java:97)
android.app.ActivityThread$H.handleMessage (ActivityThread.java:2220)
android.os.Handler.dispatchMessage (Handler.java:107)
android.os.Looper.loop (Looper.java:237)
android.app.ActivityThread.main (ActivityThread.java:8016)
java.lang.reflect.Method.invoke (Method.java)
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:493)
com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1076)