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.
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
Please check Notifications document in Android Developers site. You can display Notification during Internet Connectivity Change or during Device Reboot,or during Device Shutdown.