开发者

Android: application global onPause() and onResume()?

开发者 https://www.devze.com 2022-12-16 04:07 出处:网络
Is there something like an application global onPause() and onResume()? My main activity listens for GPS fixes, which I want to continue working when switching to another screen/activity. Therefor I

Is there something like an application global onPause() and onResume()?

My main activity listens for GPS fixes, which I want to continue working when switching to another screen/activity. Therefor I cannot unregister my LocationListener in the activity's onPause(). However I still want to unregister my GPS listener when switching to another application (so save 开发者_JAVA百科battery) and turning it back on when returning to my application, regardless what screen/activity the user is currently in.

Any ideas?


Is there something like an application global onPause() and onResume()?

No, sorry.

My main activity listens for GPS fixes, which I want to continue working when switching to another screen/activity. Therefor I cannot unregister my LocationListener in the activity's onPause(). However I still want to unregister my GPS listener when switching to another application (so save battery) and turning it back on when returning to my application, regardless what screen/activity the user is currently in.

Here's one possible approach:

Step #1: Move the LocationListener logic into a Service, which the activities connect to via the local binding pattern or something. Also have at least one service call startService(), so an unbindService() won't cause the Service to go away (assuming you're using the local binding pattern).

Step #2: Have the activities call into the service during onPause() and onResume().

Step #3: Have the service maintain a reference count of outstanding activities.

Step #4: When the reference count reaches zero, have the service arrange to get woken up via a Timer and TimerTask. Also, cancel any such outstanding TimerTask if the reference count gets incremented.

Step #5: Have the TimerTask shut down GPS if it ever gets executed.

The net is that you will only release GPS after such-and-so amount of inactivity. That inactivity could be for any reason.


Use ActivityLifecycleCallbacks. Register it in your Application:

registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) = Unit
    override fun onActivityStarted(activity: Activity) = Unit
    override fun onActivityResumed(activity: Activity) {
        Log.d(TAG, "Activity resumed: $activity")
    }
    override fun onActivityPaused(activity: Activity) {
        Log.d(TAG, "Activity paused: $activity")
    }
    override fun onActivityStopped(activity: Activity) = Unit
    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = Unit
    override fun onActivityDestroyed(activity: Activity) = Unit
})
0

精彩评论

暂无评论...
验证码 换一张
取 消