2015-05-11 139 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); 
    } 
您要檢查服務是否正在運行或不類

在服務類

相關問題