How to check if an IntentService was started

家住魔仙堡 提交于 2019-12-05 17:05:37

I'd like to get to know if an Activity successfully started an IntentService.

If you don't get an exception in either the activity or the service when you call startService(), then the IntentService was started.

As it's possible to bind an IntentService via bindService() to keep it running

Why?

Carlos Silva

Here's the method I use to check if my service is running. The Sercive class is DroidUptimeService.

private boolean isServiceRunning() {
    ActivityManager activityManager = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
    List<ActivityManager.RunningServiceInfo> serviceList = activityManager.getRunningServices(Integer.MAX_VALUE);

    if (serviceList.size() <= 0) {
        return false;
    }
    for (int i = 0; i < serviceList.size(); i++) {
        RunningServiceInfo serviceInfo = serviceList.get(i);
        ComponentName serviceName = serviceInfo.service;
        if (serviceName.getClassName().equals(DroidUptimeService.class.getName())) {
            return true;
        }
    }

    return false;
}
MohammadReza

You can add a flag when constructing the PendingIntent, if the returned value was null, your service is not started. The mentioned flag is PendingIntent.FLAG_NO_CREATE.

Intent intent = new Intent(yourContext,YourService.class);
PendingIntent pendingIntent =   PendingIntent.getService(yourContext,0,intent,PendingIntent.FLAG_NO_CREATE);

if (pendingIntent == null){
    return "service is not created yet";
} else {
    return "service is already running!";
}

Here's the method I use to check if my service is running:

  public static boolean isMyServiceRunning(Class<?> serviceClass, Context context) {
        ActivityManager manager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                return service.started;
            }
        }
        return false;
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!