3

在一個服務中,使用handler.postdelayed或Alarmmanager的延遲執行方法。 什麼是贊成和反對。AlarmManager vs Handler.postDelayed

我有2個服務(a)做後臺處理並通過boradcast消息更新UI( (b)),它會每5秒進行一次計算並更新主屏幕小部件。

感謝

+3

@anyone pleas have courtsey to write a line before doing -1。不要表現得像鬆散 – mSO

回答

2

我發現這個音符的Android開發者網站:

http://developer.android.com/training/scheduling/alarms.html

看來,AlarmManager將是要用到的類開始服務。

關於處理程序它指出:

「對於時序,保證您的應用程序的生命週期過程中發生的操作,而不是考慮使用Handler類結合定時器和線程這種方法使Android的更好了控制系統資源「。

0

AlarmManagerHandler之間的差異是AlarmManager即使在設備處於睡眠模式時也會運行,但處理程序不會。其他要考慮的是AlarmManager會消耗更多的電池,因爲它會喚醒CPU和其他芯片。

正如我理解你的問題,你必須做一些後臺任務,即使設備處於睡眠模式,你必須使用AlarmManager。儘量保持持續時間儘可能短,這樣不會耗盡電池。您可以使用REAL_TIME類型警報作爲InExact()開始報警。

您可以通過以下鏈接簽出以供參考。

AlarmManager

Best Practices to keep device wake up

0

我建議你RxJava做到這一點。在幾行內容中,您將能夠處理延遲,而不必擔心處理程序並取消該操作。如果您必須創建多個處理程序,這也可以節省大量時間。

這將創建一個訂閱者,當訂閱者訂閱的可觀察事件發出某事時,它將調用intervalSubscriber的onNext()。

// Set up a subscriber once. Setting up the subscriber 
private Subscriber<Long> intervalSubscriber = new Subscriber<Long>() { 
    @Override 
    public void onCompleted() { 
     //Wrap up things as onCompleted is called once onNext() is over 
    } 
    @Override 
    public void onError(Throwable e) { 
     //Keep an eye open for this. If onCompleted is not called, it means onError has been called. Make sure to override this method 
    } 
    @Override 
    public void onNext(Long aLong) { 
     // aLong will be from 0 to 1000 
     // Yuor code logic goes here 

     // If you want to run this code just once, just add a counter and call onComplete when the counter runs the first time 

    } 
} 

讓我們一起創建將發射的觀察值。

//Setting up the Observable. This will make runThisOnInterval observable emit every 5 seconds on Computation Threadpool created and managed by RxJava. 

private Observable<Long> runThisOnInterval = Observable.interval(5000, TimeUnit.MILLISECONDS, Schedulers.computation()); 

好的,所以我們現在都設置好了。我們現在需要做的就是將用戶間隔訂閱者runThisOnInterval observable,以便觀察者可以開始生產並且訂戶可以消費。

簡單的撥打電話subscribe()將開始排放,它不會在主線程上完成,這給我很大的靈活性。

runThisOnInterval.subscribe(intervalSubscriber);