Android myth 1/2: Activity.onDestroy()

Please prove me wrong

There’s a common conception that onDestroymarks the end of an Android activity so that you need to cancel all your subscribers/asynctasks/whatever as soon as onDestroy fires.

I believe this is mainly due to the Fragments implementations and the dreaded IllegalStateException but I have always wondered whether you could maintain a strong reference to an activity after onDestroy and do UI stuff there.

So I did a little test there: https://github.com/martinbonnin/TestOnDestroy

private Runnable mChangeContentViewRunnable = new Runnable() {
@Override
public void run() {
Log.d(TAG, "callback!");
getResources();
setContentView(new TextView(MainActivity.this));
}
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate");
setContentView(new FrameLayout(this));

}

@Override
public void onBackPressed() {
super.onBackPressed();
Log.d(TAG, "onBackPressed");
finish();
}

@Override
protected void onDestroy() {
Log.d(TAG, "onDEstroy");
new Handler().postDelayed(mChangeContentViewRunnable, 3000);
super.onDestroy();
}

Turns out it didn’t crash… Am I missing something ?

Like what you read? Give Martin Bonnin a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.