Locking screen of Android phone results in several subsequent onPause/onResume events

ⅰ亾dé卋堺 提交于 2019-12-23 07:30:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!