在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()
方法來判斷服務是否在運行。