6

I have a android service. I want to perform some task when the user changes the application. Is there a broadcast or event, which I can listen to.

If polling is the only solution, Can anyone suggest some good polling technique.

Thanks.

BlackJack
  • 93
  • 1
  • 7
  • you should open this question for bounty. My answer is clearly not an answer worth being accepted, i am curious too about possible solutions – Boris Mocialov Jul 03 '13 at 09:36

2 Answers2

1

You can distinguish Applications by polling for top activity:

private String lastPackageName;

ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
// get the info from the currently running task
List< ActivityManager.RunningTaskInfo > taskInfo = am.getRunningTasks(1); 

     Log.d("topActivity", "CURRENT Activity ::"
             + taskInfo.get(0).topActivity.getClassName());

ComponentName componentInfo = taskInfo.get(0).topActivity;
String packageName = componentInfo.getPackageName();

if(lastPackageName != packageName){
    //Probably application changed
}

lastPackageName = packageName;

But it will be up to you how often do you poll for that information.. You could try polling for this information every time user presses back, home buttons or presses on the screen.. But it will obviously be too much and bad polling technique.

Seems like this question been asked already before without and got no sufficient answer: How to be notified when foreground (top) activity (application) changes

Source: https://stackoverflow.com/a/4753333/1276374

Community
  • 1
  • 1
Boris Mocialov
  • 3,439
  • 2
  • 28
  • 55
  • 5
    "You could try polling for this information every time user presses back, home buttons or presses on the screen" -- a service cannot detect any of those things. – CommonsWare Jul 02 '13 at 13:08
-2

Please check Notifications document in Android Developers site. You can display Notification during Internet Connectivity Change or during Device Reboot,or during Device Shutdown.

Avadhani Y
  • 7,566
  • 19
  • 63
  • 90