0
我有這Service
從我的代碼中的兩個位置開始。在Android中這是一個很好很容易的方法,只有一個服務運行
如果Service
是onStartCommand()
內,另一
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;
}
}
你有沒有考慮使用'IntentService' HTTP:// developer.android.com/reference/android/app/IntentService.html?一個IntentService'處於休眠狀態',直到它通過一個Intent接受工作。如果它接收到多個Intent,則將它們排隊並按接收順序逐個處理一個Intent。當它完成所有工作後,它會再次關閉。 – Squonk
@MisterSquonk我知道IntentService並不想排隊調用。如果一個Service已經在onStartCommand中運行,我想殺掉這些呼叫。 – Erik
我的代碼沒有看到任何問題,但是,重新設計您的實現以避免此用例(兩個位置啓動相同服務)可能會更好,而不是每次嘗試進行活動時執行條件檢查在運行時啓動服務。 – yorkw