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 scr开发者_开发技巧een from my app is displayed?
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
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);
精彩评论