2011-12-11 15 views
0

我有這Service從我的代碼中的兩個位置開始。在Android中這是一個很好很容易的方法,只有一個服務運行

如果ServiceonStartCommand()內,另一

startService由開始一遍,我需要阻止它。

在下面的代碼我設置了private boolean getFriendListRunning;

這是正確的還是我應該怎麼辦?

public class ServiceGetFriendList extends Service{ 

    private final String TAG = "ServiceGetFriendList"; 
    private IBinder mBinder; 
    private boolean failed = false; 

    private boolean getFriendListRunning; 

    @Override 
    public void onCreate() { 

    } 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 

     if(getFriendListRunning) 
      return Service.START_STICKY; 

     getFriendListRunning = true; 

     try{ 
      work...... 
      } catch (Exception e) { 

      }finally{ 

      getFriendListRunning = false; 
     } 
    } 
+0

你有沒有考慮使用'IntentService' HTTP:// developer.android.com/reference/android/app/IntentService.html?一個IntentService'處於休眠狀態',直到它通過一個Intent接受工作。如果它接收到多個Intent,則將它們排隊並按接收順序逐個處理一個Intent。當它完成所有工作後,它會再次關閉。 – Squonk

+0

@MisterSquonk我知道IntentService並不想排隊調用。如果一個Service已經在onStartCommand中運行,我想殺掉這些呼叫。 – Erik

+1

我的代碼沒有看到任何問題,但是,重新設計您的實現以避免此用例(兩個位置啓動相同服務)可能會更好,而不是每次嘗試進行活動時執行條件檢查在運行時啓動服務。 – yorkw

回答

0

我結束了使用IntentService並啓動它之前,我檢查RunningServiceInfo,看看它已在運行,而不是啓動它,如果它的運行

private boolean isIntentServiceRunning(String serv) { 
    ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE); 
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { 
     if (serv.equals(service.service.getClassName())) { 
      return true; 
     } 
    } 
    return false; 
} 
相關問題