Question

I have looked around, but all suggestions are for checking state of my own app/activity. using the Life Cycle. I need to check if another app is in foreground/ running in background / paused . Is it possible. Based on the state of the app i need to change my further actions.

Was it helpful?

Solution

ActivityManager acm=(ActivityManager) getSystemService(ACTIVITY_SERVICE);
List< ActivityManager.RunningTaskInfo > taskInfo = acm.getRunningTasks(1); 
taskInfo.get(0).topActivity.getClassName();
ComponentName componentInfo = taskInfo.get(0).topActivity;
String packageName=componentInfo.getPackageName();

I used Activity manager to find the top package / activity if this matches the requrements i send a broadcast to the app that will update the info from the db. This can simply be done by registering a broadcast receiver using code in the onResume and Unregister it in OnPause. So checking the Top package has just become a double check.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top