2015-05-11 134 views
0

我正在使用IntentService来调用Web服务。IntentService在检查服务是否正在运行时返回False

如何,我打电话来启动意图服务:

if (isMyConServiceRunning(TaskService.class,context) == false) { 
      Log.d(TAG,"STARTING TaskService"); 
      context.startService(TasksIntentUploadDownload); 
     } 

isMyConServiceRunning方法:

private static boolean isMyConServiceRunning(Class<?> serviceClass,Context context) 
    { 
     try { 
      ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); 
      for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { 
       if (serviceClass.getName().toLowerCase(Locale.ENGLISH).contains(service.service.getClassName().toLowerCase(Locale.ENGLISH))) { 
        return true; 
       } 
      } 
     } 
     catch(Exception e) 
     {} 
     return false; 
    } 

isMyConServiceRunning总是返回false(该服务没有运行),因此服务正在启动多个倍,但我注意到,当我重写方法OnStartCommand并将Web服务调用OnStartCommand而不是OnHandleIntent并使OnStartCommand返回START_STICKY,则isMyConServiceRunning将认识到该服务正在运行。

运行OnStartCommand中的任务是不是很糟糕?

如果是,我该如何修复多个呼叫来运行IntentService

+0

为什么你检查服务已经运行? –

+0

我正在检查服务是否没有运行,然后如果它不是我开始服务 –

+0

,并且上面一直返回false –

回答

0

一个更好的办法是:

private void sendMessageStart() { 

     Intent intent = new Intent("Service-Started"); 
     intent.putExtra("message", "This is my message!"); 
     LocalBroadcastManager.getInstance(this).sendBroadcast(intent); 

    } 
    private void sendMessageStop() { 

     Intent intent = new Intent("Service-Stopped"); 
     intent.putExtra("message", "This is my message!"); 
     LocalBroadcastManager.getInstance(this).sendBroadcast(intent); 
    } 
您要检查服务是否正在运行或不类

在服务类

相关问题