I encountered this somewhat strange behavior while developing on Android and during my googling the only answer I could find was that this is by design and that I should not care about it.
My application fetches location data while active, and I was about to implement a way to preserve battery by stopping location updates when the onPause event is called, and later resume fetching when the onResume event is called.
While debugging I noticed this strange behavior when locking the phone, onPause->onResume get called one after another three or more times and then end with a onStop event. The only answer I where able to find was like: that's how android works, nevermind.
I guess I'm curious, can someone explain me the need to stop and resume a simple sub-activity several times? Doesn't that consume more battery, especially for larger activities that have serious code in onResume? Is there a way to prevent this from happening? I would be happy just by knowing that at least my code in those events doesn't get called, maybe with a if{} block preventing unnecessary CPU cycles.
Any insight is greatly appreciated!
onResume() is one of the methods called throughout the activity lifecycle. onResume() is the counterpart to onPause() which is called anytime an activity is hidden from view, e.g. if you start a new activity that hides it. onResume() is called when the activity that was hidden comes back to view on the screen.
onPause. Called when the Activity is still partially visible, but the user is probably navigating away from your Activity entirely (in which case onStop will be called next). For example, when the user taps the Home button, the system calls onPause and onStop in quick succession on your Activity .
onPause() is called when an activity is about to lose focus. onStop() is called when the activity is has already lost the focus and it is no longer in the screen. But onPause() is called when the activity is still in the screen, once the method execution is completed then the activity loses focus.
You have to register broadcast receiver for handling "Screen Time Out" and "Screen Lock" events.
You just stop your data retrieving. Sample code:
public class ScreenReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
//screen locked, do here
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
//screen unlocked, do something here
}
}
}
You need to register broadcast receiver for this ScreenReceiver class to the androidMenifest.xml
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With