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).
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?
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.
- 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?
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). 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.
- 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
.