Yaroslav Yaroslav - 1 year ago 95
Android Question

Android callback methods: When? How? From wheech Thread?

I don't know/understand something about Android callback methods and their implementation.

I have a simple Activity with implemented callbacks like:

onResume() {
Log.i(TAG, "onPause()");

onDestroy() {
Log.i(TAG, "onDestroy()");

onButtonPressed() {
while(true) {
Log.i(TAG, "onButtonPressed()");

When I start my App and change screen orientation I can see onPause() and onDestroy() logs in console.
But, when I press test button (onButtonPressed()) and a long lasting procedure starts (while true) I can see in console only onButtonPressed() logs. I can rotate my phone, and I see that activity is turned according to orientation, but no calls to callbacks onDestroy() and onPause() (no logs in console).

Is my Activity still recreated during orientation change? Why callbacks are not called? Are they called on some other thread?

Can anyone clarify for me this situation and explain how exactly Android performs calls to callback methods?

Tested on AndroidN.

Thank You.

Looks like it was a mistake from my side.
When I was rotating my phone, I saw that screen is rotating, but haven't understood that activity isn't... It was just placed on one side of screen (sought it was a developer preview bug on Android N). And that confused me :D

enter image description here

Thanks for answer and help.

Answer Source

Unless specified otherwise in documentation all method calls and callbacks are typically handled on the main thread (UI thread).

This goes for all the life cycle methods such as onResume() and onDestroy() in your example as well as UI callbacks such as onButtonPressed().

In the second example where you enter the infinite while loop, you completely tie up the UI thread so none of the life cycle methods can run anymore and the user can no longer interact with the application. This is why when you rotate the device you do not see the log statements being printed. The current Activity is never destroyed and a new Activity cannot be created because you have the thread responsible for doing so in an infinite loop.

This is also why Android documentation recommends moving all long running operations off the UI thread so that you do not negatively impact the user's experience.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download