如何检查是否已启动IntentService

cod*_*ody 4 android intentservice

我想知道一个Activity是否成功启动了IntentService.

由于可以绑定IntentService通道bindService()以使其保持运行,因此可能的方法是检查是否在服务对象startService(intent)的调用onStartCommand(..)或调用中调用结果onHandleIntent(..).

但是如何在活动中检查?

小智 7

这是我用来检查我的服务是否正在运行的方法.Sercive类是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;
}
Run Code Online (Sandbox Code Playgroud)


Moh*_*eza 5

您可以在构造时添加标志PendingIntent,如果返回的值是null,则表示您的服务未启动.提到的旗帜是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!";
}
Run Code Online (Sandbox Code Playgroud)