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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With