22

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

Alex
  • 2,213
  • 4
  • 32
  • 44

2 Answers2

6

AFAIK there are two ways to do that.

  1. Start a service and monitor the Activity Stack, you might check it here
  2. Use an Accessibility Service, you could find a solution here
Community
  • 1
  • 1
Kevin
  • 366
  • 4
  • 5
  • 1
    Note 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
  • 1
    Well 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
  • @Alex, you can use this technique to do that, but you need to poll. – Sam May 04 '15 at 10:51