在Android中,可以通过以下方法判断服务是否在运行:
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> runningServices = activityManager.getRunningServices(Integer.MAX_VALUE);
for (ActivityManager.RunningServiceInfo serviceInfo : runningServices) {
if (serviceInfo.service.getClassName().equals(YourService.class.getName())) {
// 服务正在运行
break;
}
}
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo serviceInfo : activityManager.getRunningServices(Integer.MAX_VALUE)) {
if (YourService.class.getName().equals(serviceInfo.service.getClassName())) {
// 服务正在运行
break;
}
}
public class YourService extends Service {
private static boolean isRunning = false;
@Override
public void onCreate() {
super.onCreate();
isRunning = true;
}
@Override
public void onDestroy() {
super.onDestroy();
isRunning = false;
}
public static boolean isRunning() {
return isRunning;
}
}
然后在其他地方通过调用YourService.isRunning()
方法来判断服务是否在运行。