I want to write a service for Android platform that is notified when the current foreground activity changes. Basically the service should do some tasks only when the top activity changes. Is there any way to subscribe and to be notified when this kind of event occurs ? Or there is no possibility and the service should poll from time to time the list of running activities and to check what is the foreground activity ?Not preferable solution...
Asked
Active
Viewed 8,939 times
22
-
On what platform are your trying to write your service ? – Guillaume Oct 06 '10 at 09:30
-
2Did you ever find a solution for this? I'm trying to do something similar. – harbinja Dec 14 '11 at 16:00
-
Did you look into the logcat output? I assume the ActivityManager is always involved when foreground activity changes, so this might be visible from the log. – ovenror Sep 10 '13 at 13:18
-
@Alex Did you ever get to solve this? – benkol Dec 18 '13 at 14:10
2 Answers
6
AFAIK there are two ways to do that.
-
1Note that the linked technique for polling for the current activity doesn't work in Android 5+. – Sam Apr 27 '15 at 09:20
-
@Sam Then how the application that protects selected application work? How they detect when an application comes and foreground? Thank you – Ashraf Alshahawy Aug 11 '16 at 13:58
-
@Astrount, I don't know what developers use these days, but the last time I checked, option 2 in this answer still works in Android 5. – Sam Aug 14 '16 at 08:20
0
You should bind every activity to the service and you will know which activity is running.
try this:
List runningTaskInfos=actvityManager.getRunningTasks(1).get(i).topActivity .getPackageName();
this method will give info of activity's package name which is in foreground..............

Paolo Stefan
- 10,112
- 5
- 45
- 64

fedj
- 3,452
- 1
- 22
- 21
-
1Well this is not a solution, maybe I've expressed myself wrong, I want that the service be notified what application is running in the foreground (it could be any of the installed applications) and compare with a predefined list of applications and if it is on the list to do some work. – Alex Oct 06 '10 at 10:13
-
Ah ok, you wrote Activity so I understood that it was only one application. I really don't know how to do what you want to do sorry – fedj Oct 06 '10 at 10:56
-