检查服务是否已经在运行

时间:2018-08-28 08:39:27

标签: android

我在我的android应用程序的Application类中启动了一项服务。

该服务每小时运行一次,我不希望每次打开应用程序时都启动该服务,这似乎是它现在正在做的事情。我想检查它是否正在运行,如果不是,请运行它。

I found this code在另一个我认为可行的答案中,但是如果我两次运行该应用程序,仍然会从以下代码中收到消息“服务未运行,作业已计划”:

public class App extends Application {

    public static final String TAG = "Application";
    public static final int JOB_NUMBER = 3007;

    @Override
    public void onCreate() {
        super.onCreate();
        if(!isMyServiceRunning(DevotionalService.class)) {
            ComponentName componentName = new ComponentName(this, DevotionalService.class);
            JobInfo info = new JobInfo.Builder(JOB_NUMBER, componentName)
                    .setRequiresCharging(false)
                    .setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
                    .setPersisted(true)
                    .setPeriodic(60 * 60 * 1000)
                    .build();
            JobScheduler scheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
            int resultCode = scheduler.schedule(info);
            if (resultCode == JobScheduler.RESULT_SUCCESS) {
                Log.d(TAG, "Service is not running, Job Scheduled.");
            } else {
                Log.d(TAG, "Service is not running, However job scheduling failed.");
            }
        } else {
            Log.d(TAG, "Service is already running.");
        }
    }

    private boolean isMyServiceRunning(Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }

    public void cancelJob() {
        JobScheduler scheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
        scheduler.cancel(JOB_NUMBER);
        Log.d(TAG, "Job Cancelled.");
    }
}

有人对这可能是为什么有任何见识吗?

1 个答案:

答案 0 :(得分:3)

要检查服务是否正在运行:

class MyService extends Service {
   private static boolean isRunning;
   public int onStartCommand (Intent intent, 
                int flags, 
                int startId) {
        isRunning = true;
        ...
   }
   public void onDestroy() {
       isRunning = false;
   }
   public static boolean isRunning() { 
       return isRunning;
   }
}

然后要检查其运行情况,只需检查MyService.isRunning()

要检查是否已安排服务:

if(JobScheduler.getPendingJob(jobID) == null) {
   //job notscheduled
}