views:

785

answers:

2

I have implemented a BroadcastReceiver which is triggered by the AlarmManager. The AlarmManager is initialized on BOOT_COMPLETED. So i have to declare the receiver in the manifest.

My problem is that i want the BroadcastReceiver only to do something when none of my own activities are in the foreground (aka the user is not interacting with my application). I pull information from a remote server and don't want to notify the user if he is currently in my application anyways.

So far i have not managed to find a way to determine if my application is in the foreground. Is there a way to do such thing? The ActivityManager tells me if my application is running but not whether it is in the foreground.

The problem is pretty much the same as described here: http://stackoverflow.com/questions/2282435/inform-activity-from-a-broadcastreceiver-only-if-it-is-in-the-foreground

A: 

Your activity can track its own state as to whether it is in the foreground (set boolean to true in onStart(), to false in onStop()). Alas, that boolean is not provided to you by Activity automatically.

CommonsWare
That would be possible but every Activity in my application would support that scenario. Also i don't want to couple this behavior to my activities but rather have the BroadcastReceiver determine the actual state.
Soulreaper
A: 

ActivityManager#getRunningAppProcesses() returns a List of RunningAppProcessInfo. Each RunningAppProcessInfo has a field called importance. importance equal to RunningAppProcessInfo.IMPORTANCE_FOREGROUND seems to show which activity is actively being observed by the user. There is also RunningAppProcessInfo.IMPORTANCE_VISIBLE which is lower but might be worth checking out.

jqpubliq
Thanks. I will look into that.
Soulreaper
After investigating the possibilities of the RunningAppProcess it turned out that the importance of the processes never changes. For my activity the importance has always been IMPORTANCE_FOREGROUND (100). That applied when the activities has not been started at all, the activity is active in the foreground or the activity stack is send to the back. No changes in the importance value.So sadly this is not a solution for my problem. :( Any other ideas?
Soulreaper
I tried starting up one of my projects and then popping another one on top of it and the one in the background did go to IMPORTANCE_BACKGROUND(400). It only seems to show package name of the whole project as well. Is your service part of the package that you are trying to check? maybe having the debugger attached is elevating the importance or something.
jqpubliq
Interesting that you describe it to work. Maybe it makes a difference since i am checking the processes from a BroadcastReceiver and not from the activity itself.Btw, i am testing on the emulator in regular launch mode.
Soulreaper