我想知道活动是否成功启动IntentService
。如何检查IntentService是否已启动
由于这是一个可以通过IntentService
bindService()
绑定到它的持续运作,也许是一个办法是检查是否在onStartCommand(..)
或onHandleIntent(..)
在服务对象的调用调用startService(intent)
结果。
但我该如何检查活动?
我想知道活动是否成功启动IntentService
。如何检查IntentService是否已启动
由于这是一个可以通过IntentService
bindService()
绑定到它的持续运作,也许是一个办法是检查是否在onStartCommand(..)
或onHandleIntent(..)
在服务对象的调用调用startService(intent)
结果。
但我该如何检查活动?
我想了解如果活动成功启动的IntentService。
如果您在拨打startService()
时未在活动或服务中发现异常,则启动IntentService
。
因为它有可能通过绑定的bindService IntentService(),以保持其运行
为什么?
以下是我用来检查服务是否正在运行的方法。 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;
}
谢谢..但是这不是我在寻找 - 我需要检查,如果startService()被调用,如果服务实际上正在运行,则不是... – cody
Hummm,他们必须让您的服务广播和意图告诉您它已启动。看起来像是我唯一的选择。 –
您可以在构建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!";
}
这只有在您开始使用PendingIntent进行服务时才有效,例如使用AlarmManager,该FLAG的文档声明:标志表示如果所描述的PendingIntent尚不存在,则只需返回null而不是创建它。长时间运行的服务将无法正常工作 – JavierSP1209
下面是我用它来检查,如果我的服务正在运行的方法:
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;
}
我只想确保服务已启动。谢谢 – cody