代码之家  ›  专栏  ›  技术社区  ›  Chud37

检查服务是否已在运行

  •  1
  • Chud37  · 技术社区  · 6 年前

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

    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 回复  |  直到 6 年前
        1
  •  6
  •   Gabe Sechan    6 年前

    要检查服务是否正在运行,请执行以下操作:

    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
    }