How to check if an IntentService was started

眉间皱痕 提交于 2019-12-22 08:59:46

问题


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

As it's possible to bind an IntentService via bindService() to keep it running, perhaps an approach would be to check if invoking startService(intent) results in a call of onStartCommand(..) or onHandleIntent(..) in the service object.

But how can I check that in the Activity?


回答1:


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?




回答2:


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;
}



回答3:


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!";
}



回答4:


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;
    }


来源:https://stackoverflow.com/questions/7060793/how-to-check-if-an-intentservice-was-started

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!