2

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?

Lysandus
  • 764
  • 4
  • 23

3 Answers3

5

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

pandre
  • 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
3

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.

Community
  • 1
  • 1
jkhouw1
  • 7,320
  • 3
  • 32
  • 24
1

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);
includeMe
  • 2,672
  • 3
  • 25
  • 39