2015-04-29 18 views
4

我試圖在幾次重啓服務。我的代碼看起來像這樣(的onStartCommand(...)內)postDelayed()服務

Looper.prepare(); 
Handler handler = new Handler(); 
handler.postDelayed(new Runnable() { 
      @Override 
      public void run() { 
       Intent intent = new Intent(BackgroundService.this, BackgroundService.class); 
       startService(intent); 
      } 
     }, 3 * 60000); 

服務在前臺運行時,該代碼執行,但它似乎並沒有打電話給onStartCommand(...)。 有沒有其他方法可以在幾秒內重新啓動服務?

UPD:我發現,它實際上重啓服務,而不是在給定的時間(可能需要長達30分鐘,而不是給出3)。所以,現在的問題是如何使它重新啓動因此由處理器計劃

回答

2

操作不能始終如一地運行,因爲該設備可能在此刻睡覺。安排背景中的任何延遲行動的最佳方法是使用系統AlarmManager

在這種情況下,代碼必須使用以下改爲:

AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 

Intent alarmIntent = new Intent(BackgroundService.this, BackgroundService.class); 

PendingIntent pendingIntent = PendingIntent.getService(BackgroundService.this, 1, alarmIntent, 0); 

alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 3 * 60, pendingIntent); 
2

我會在服務級別聲明處理程序變量,不是本地的onStartCommand,如:

public class NLService extends NotificationListenerService { 
    Handler handler = new Handler(); 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     handler.postDelayed(new Runnable() {....} , 60000); 
    } 

而且服務有其自身的循環,所以你不需要Looper.prepare();

1

替換

Handler handler = new Handler(); 

隨着

Handler handler = new Handler(Looper.getMainLooper()); 

爲我工作。