Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Detect Activity/Application Change Events [duplicate]

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.

like image 974
BlackJack Avatar asked Jul 02 '13 12:07

BlackJack


1 Answers

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

like image 165
Boris Mocialov Avatar answered Oct 07 '22 01:10

Boris Mocialov