How to detect if any of my activity is front-most and visible to user?

前端 未结 5 1276
醉酒成梦
醉酒成梦 2020-11-29 08:19

I would like to launch an intent when any of my activity is visible, otherwise I will put it up as a notification, and will be fired by the user.

To decide this, I

5条回答
  •  北海茫月
    2020-11-29 08:51

    Instead of using Activity manager there is a simple trick which you can do through code. If you observe the activity cycle closely, the flow between two activities and foreground to background is as follows. Suppose A and B are two activities.

    When transition from A to B: 1. onPause() of A is called 2. onResume() of B is called 3. onStop() of A is called when B is fully resumed

    When app goes into background: 1. onPause() of A is called 2. onStop() of A is called

    You can detect your background event by simply putting a flag in activity.

    Make an abstract activity and extend it from your other activities, so that you wont have to copy paste the code for all other activities wherever you need background event.

    In abstract activity create flag isAppInBackground.

    In onCreate() method: isAppInBackground = false;

    In onPause() method: isAppInBackground = false;

    In onStop() method: isAppInBackground = true;

    You just to need to check in your onResume() if isAppInBackground is true. n after you check your flag then again set isAppInBackground = false

    For transition between two activities since onSTop() of first will always called after second actvity resumes, flag will never be true and when app is in background, onStop() of activity will be called immediately after onPause and hence the flag will be true when you open the app later on.

提交回复
热议问题