简体   繁体   中英

How to know from context values which activity is currently running foreground?

I have a tricky situation. I will try to fully explain it in the best possible way.

My app has few activities, say A, B, C. A is the Main Activity and B & C gets called from A. So basically when B or C is running, A will be stopped(onStop()).

I am using an android library(created by me) in my App. My library saves the contexts of the activities. For example, when we open the app with activity A, my library will save A's context and will create a handler using that context and save them in a Map( Map<Context, Handler >). Now if we navigate to activity B, my library will get B's context and then make a new entry for this in the Map.

At some point in time, I will use the handlers present in the Map to post some runnables. Obviously, both A and B will receive as both are running(one in background and foreground).

  1. But how can I check and send only to the one running in the foreground? Is it possible to check from a context value, whether the activity is currently running or stopped?

  2. Does this.getMainLooper when called from A and B return the same thing?

UPDATE: I am sorry, I missed this point. The App is a demo application on how to use my library. So I will release my library in future and developers will be using it. Hence I don't want the developers to do this and it would be the best if I can do it in my library itself.

  1. But how can I check and send only to the one running in the foreground? Is it possible to check from a context value, whether the activity is currently running or stopped?
  • The easiest and recommended way will be to hand a reference to the Application object to your library, with it you can register to Activity Lifecycle callbacks using Application.registerActivityLifecycleCallbacks , and monitor the state of the Activities and determine when activity is foreground (using onActivityResumed() callback).
  • Another less preferable option, is that each activity will notify your library code about it's events, but it's of course more tedious and error prone.
  • Third 'do not do it' way is to use ActivityManager that has getRunningTasks() , and from their you can get top activity, but again it's documented as for 'debug purposes only' and is more error prone then all the above.
  1. Does this.getMainLooper when called from A and B return the same thing?

Yep, A and B sitting on the same process, Main Looper is the looper of the main UI thread, which is singular per Process .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM