开发者

Android how to distinguish application in background and activity in background?

开发者 https://www.devze.com 2023-04-02 02:09 出处:网络
Is there any way to get different event for application in background and particular activity in background?

Is there any way to get different event for application in background and particular activity in background?

In other words when any activity goes to background the onPause() method called, is there any to find that whole application goes to background?

Is there any settings for Manifest file to开发者_StackOverflow close the application when its goes to background.

Thanks,

AndroidIT


To identify if the application is in background:

There is a much more simpler approach:

On a BaseActivity that all Activities extend:

protected static boolean isVisible = false;

 @Override
    public void onResume()
    {
        super.onResume();
setVisible(true);
}


 @Override
    public void onPause()
    {
        super.onPause();
setVisible(false);
}

Whenever you need to check if any of your application activities is in foreground just check isVisible();

To understand this approach check this answer of side-by-side activity lifecycle: Activity side-by-side lifecycle

If you want to kill your application when it goes to background you have several options:

  1. Something like this: Remove or close your own Activity window from a Status Bar Notification Intent modified for what you want.
  2. Explore: android:finishOnTaskLaunch and android:excludeFromRecents and how you can make logic to make this effect (have done it already)


I would assume that all your activities are launched by one of the other activities in your app. If that is the case perhaps your activities could set flag indicating it is launching an activity. Then when onpause() is called this flag will determine if the app is being move to the background or simply launching the next activity.


save the state of each activity in shared preferences. each activity will need its own field in the preference file. each time you onResume or onPause, update the correct preference.

or: every time you onResume or onPause send a service a notification via intent that X activity has paused/resumed. the service will keep track of application state this way

0

精彩评论

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

关注公众号