在一个服务中,使用Handler.postDelayed还是AlarmManager延迟执行的方法。其优缺点是什么。
我有两个服务: (a) 后台处理并通过广播消息更新UI; (b) 进行一些计算,并每5秒更新主屏幕小部件。
谢谢。
我有两个服务: (a) 后台处理并通过广播消息更新UI; (b) 进行一些计算,并每5秒更新主屏幕小部件。
谢谢。
http://developer.android.com/training/scheduling/alarms.html
似乎AlarmManager是启动服务的类。AlarmManager
和 Handler
的区别在于,AlarmManager
即使设备处于睡眠模式也会运行,而 Handler
不会。另一个要考虑的因素是,AlarmManager
会消耗更多的电池电量,因为它会唤醒 CPU 和其他芯片。// 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());
好的,现在我们已经准备就绪了。我们现在只需要将intervalSubscriber订阅到runThisOnInterval可观测对象上,这样可观测对象就可以开始产生数据,而订阅者则可以消费数据。
简单调用subscribe()
即可开始发射数据,而且它并不是在主线程上执行,这给了我很大的灵活性。
runThisOnInterval.subscribe(intervalSubscriber);