I have an Android app with a service that runs in the background doing various client/server connections. How can I check in my running service if any screen from my app is displayed?
3 Answers
You can get the list of running processes and check if yours is in foreground with the following code:
ActivityManager actMngr = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List<RunningAppProcessInfo> runningAppProcesses = actMngr.getRunningAppProcesses();
for (RunningAppProcessInfo pi : runningAppProcesses) {
if (getPackageName().equals(pi.processName)) {
boolean inForeground = pi.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
}
}
Check more at http://developer.android.com/reference/android/app/ActivityManager.RunningAppProcessInfo.html

- 6,685
- 7
- 42
- 50
-
You may want IMPORTANCE_VISIBLE, not FOREGROUND, in case your app is visible but has a dialog from another service on top of it. – Glenn Maynard Apr 04 '13 at 01:23
Refreshing an Activity from service when Active a few options:
•Have the activity register a listener object with the service in onResume() and remove it in onPause()
•Send a private broadcast, picked up by the activity via registerReceiver() when it is in the foreground
•Have the activity supply a "pending result"-style PendingIntent to the service
•Use a ResultReceiver
•Use a ContentProvider, with the activity holding onto a Cursor from the provider, and the service updating the provider
see here https://github.com/commonsguy/cw-advandroid/tree/master/AdvServices/ for a few examples.
To check whether a service is running use
ActivityManager manager = (ActivityManager) MyApp.getSharedApplication().getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (CTConstants.MyService_Name.equals(service.service.getClassName())) {
//Your service is running
}
}
if you don't want to generalize this as a common function then replace the first line with
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);

- 2,672
- 3
- 25
- 39