Random Android Learnings

Follow my Medium page at https://medium.com/@ghbhatt


Activity lifecycle on rotation

We all learn that on rotation the Activity undergoes destruction and re-creation. To handle this, we often have listeners / weak references to the Activity that is detached and reattached in the onStop() and onStart() methods. These listeners are invoked when a long running task returns e.g your network call.

In an interview, I was asked a question: what would happen if the call returned right at the time when the activity is destroyed but the new instance is not yet created? i.e what would happen when your long running task returned between the onStop() of the Activity being destroyed and onStart() of the Activity being recreated? At first, I was confused because it seemed like a really legit use case and I was wondering why I never thought about it. Needless to say, I didn't do well in that interview trying to give a really weird timing based solution but on the bright side, I learned a really valuable concept.

However, I then learned that the destruction and corresponding creation commands for the Activity are run on a single message on the UI thread. In other words, when the device is rotated, the Android system queues up the onPause() (of the destroying Activity) to onResume() (of the newly created Activity) calls in one message thus guaranteeing that any kind of callback messages will be posted at the earliest on the next message on the UI thread which in turn makes sure that the Activity and all its views are available at your disposal.

I believe this is important information to know when you're making architectural decisions in your app. I also want to call out and share some love with the people who designed it this way, making our lives easier!

Comments

Popular posts from this blog

MY Pursuit

Value of Education and Education of Values