Get onPause & onResume like events at application/task level

喜欢而已 提交于 2019-12-05 02:30:13

Use Handler instead of TimerTask. A timed message for a Handler bound to an Activity's Looper will not be triggered if the activity is not active.

The pattern would be to send a timed message to the Handler which would in turn spawn a Thread/AsyncTask which would execute the request in the background and update the UI. A bit more overhead in thread creation/destruction but this is I/O bound anyway. You could make a thread pool if that overhead becomes a bototleneck (though I doubt it would).

If you really want to know when your application is no longer in the foreground, you can use the overlap in onStop/onResume between two activities. When going from A->B, B's onResume will be called before A's onStop. Therefore, you can increment a global counter in onResume and decrement it in onStop. That counter will become 0 if and only if no activities are visible. I used this successfully to track precise visits for analytics purposes. It does require a common base class for all your activities, though.

Are you talking about android.app.Application class? There's single Application created when your app starts, before starting some Activity or Service, and it lives as long as your app remains in memory.

You may extend this Application and put there some global data. Specify in manifest in <application android:name=".YourApp"> the name of your extended class.

Now you should understand, that Application as such doesn't go to foreground or background, only Activity can. However, from your Activity, you can call getApplication to get your single Application instance (use casting), and call your own methods related to focus change, thus knowing if your app as a whole is in foreground or background, and behave as needed.

And Service has also getApplication() method, which receives same Application object.

Most developers probably don't realise that they can have single Application object keeping needed app data, not only bunch of Activities and Services.

If you want to do some background task that has application level scope then you should be launching a new thread on a Service to do this task for you.

The Service is independent from any Activity and so will continue to run your task thread until you stop the it.

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