android: 检测一个服务是否在运行?

如何检测Android中的后台服务正在运行?我想要一个android的activity来切换服务的状态——如果关闭了我可以把它打开,如果服务器开着我可以把它关闭。怎么实现啊?

在一个activity中使用如下代码:

private boolean isMyServiceRunning() {
    ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if ("com.example.MyService".equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}

我之前也遇见过类似的问题,用下面这段程序解决了的,希望也能解决你的问题。

import os 
import subprocess 
import re 

def findThisProcess( process_name ): 
  ps     = subprocess.Popen("ps -eaf | grep "+process_name, shell=True, stdout=subprocess.PIPE) 
  output = ps.stdout.read() 
  ps.stdout.close() 
  ps.wait() 

  return output 

# This is the function you can use   
def isThisRunning( process_name ): 
  output = findThisProcess( process_name ) 

  if re.search('path/of/process'+process_name, output) is None: 
    return False 
  else: 
    return True 

# Example of how to use 
if isThisRunning('some_process') == False: 
  print("Not running") 
else: 
  print("Running!") 

你必须为服务调用startService()方法,来正确注册。只通过BIND_AUTO_CREATE是不够的。

 Intent bindIntent = new Intent(this,ServiceTask.class); 
 startService(bindIntent); 
 bindService(bindIntent,mConnection,0); 

然后是ServiceTools class:

public class ServiceTools { 
    private static String LOG_TAG = ServiceTools.class.getName(); 

    public static boolean isServiceRunning(String serviceClassName){ 
        final ActivityManager activityManager = (ActivityManager)Application.getContext().getSystemService(Context.ACTIVITY_SERVICE); 
        final List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE); 

        for (RunningServiceInfo runningServiceInfo : services) { 
            if (runningServiceInfo.service.getClassName().equals(serviceClassName)){ 
                return true; 
            } 
        } 
        return false; 
     } 
}