问题
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!
回答1:
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
回答2:
I recently ran into the same issue and was able to stop it from happening by playing with Config changes for the activity in the manifest file. I believe that when a user locks a device, a few things can happen: The orientation can change, the screen size can change (if navigation or notification bars disappear), etc. and that causes Android to rebuild all activities & fragments. I ended up selecting a lot of the options in Config changes and it stopped calling onResume after onPause.
来源:https://stackoverflow.com/questions/11290018/locking-screen-of-android-phone-results-in-several-subsequent-onpause-onresume-e