没有选用TimerTask,而是选用Rxjava的定时器。
先上代码:
upDateCache = Observable.interval(0, 1, TimeUnit.SECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Long>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Long aLong) {
}
});
然后再Activity的onDestory中取消订阅
if (upDateCache != null && !upDateCache.isUnsubscribed()) {
upDateCache.unsubscribe();
upDateCache = null;
}
出现的问题是,从该Activity返回时,onDestory()里面正确执行了,但是定时器却没有关闭,Log还在继续不停的打出来。
为此找到一个方法,首先:
compile ‘com.trello:rxlifecycle:0.3.0’
compile ‘com.trello:rxlifecycle-components:0.3.0’
compile ‘io.reactivex:rxandroid:1.0.1’
compile ‘io.reactivex:rxjava:1.0.16’
其次是:需要当前的Activity继承RxAppCompatActivity。
upDateCache = Observable.interval(0, 1, TimeUnit.SECONDS)
**.compose(this.<Long>bindToLifecycle())**
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Long>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Long aLong) {
}
});
添加了这句话,可以使定时器跟随当前的Activity的生命周期而变化。
所以onDestory中的取消订阅也可以直接删除。
当然还有:使用bindUntilEvent指定在哪个生命周期方法调用时取消订阅。