Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android's activity lifecycle after coming out of sleep

If an activity is being shown on the screen and has a button with a click listener attached to it, that gets attached to the button during the onCreate method, and then the device goes into sleep mode (or the user taps on the power button to turn off the screen), when the screen comes back on the activity is still visible as it was prior to going into sleep mode.

The onResume gets called, which is documented as part of the lifecycle for an activity. What I don't understand is why the onCreate doesn't get called again. How is it possible for the button's click listener to even function after coming out of sleep mode? You would think that Android has destroyed all running processes attached to the activity which includes the button's click listener.

like image 863
Johann Avatar asked Jul 06 '13 06:07

Johann


1 Answers

What do you mean by, why doesn't the onCreate() get called again?

Simple answer: your activity is not being destroyed when the screen goes off, so there is no reason for onCreate() to be called again.

When the phone's screen is turned off, the activity's onPause() callback is called, followed by onStop(). However, just because it reaches onStop() does not mean that it will always reach onDestroy(). At least to my understanding, Android's OS attempts to keep as much of its memory used as possible so that apps will load back up faster, etc (this is a real over simplification, but I believe that is the general idea). That means that your activity still exists in memory when the screen goes off (at least at the beginning). Only when the system really needs the resources that your activity holds will it call your activity's onDestroy(). That is why your button click listener still works when you turn the screen off. Your activity still exists in memory, which means that your button listener is also still registered.

I think it's important to point out that sleep mode and turning off the screen are not the same thing. When you turn the screen off, it may or may not go into sleep mode right away. When the screen goes off but it doesn't go into sleep mode yet, the cpu is still working and the service is still running. When the phone goes into sleep mode it powers down the CPU, essentially "freezing" all processes, and as a result all services also. Using wakelocks prevents the phone from going into sleep mode, which is why services will still run while the phone's screen is off for an extended period of time. If you haven't read it yet, the Service reference has some pretty good info. It also discusses its lifecycle and how Android prioritizes its memory usage.

like image 114
btse Avatar answered Oct 05 '22 13:10

btse