Android服务中如何取消嵌套CountDownTimer?解决空指针异常
解决Service中CountDownTimer取消时的空指针问题
嘿,这个空指针问题其实很好理解——你看,theGraceCountDownTimer是在theFirstCountDownTimer的onFinish()方法里才被实例化的对吧?如果Service在第一个定时器还没跑完的时候就被销毁了,那第二个定时器根本还没被创建,此时它的引用还是null,直接调用cancel()肯定会触发空指针异常。
快速修复方案
修改你的onDestroy()方法,在调用cancel()之前先做非空判断:
@Override public void onDestroy(){ // 只有当第二个定时器已经被初始化时,才执行取消操作 if (theGraceCountDownTimer != null) { theGraceCountDownTimer.cancel(); } // 第一个定时器虽然在onStartCommand里初始化了,但保险起见也加个判断 if (theFirstCountDownTimer != null) { theFirstCountDownTimer.cancel(); } super.onDestroy(); }
额外优化小技巧
为了避免不必要的内存占用,你可以在定时器执行完成后主动清空引用:
比如在theGraceCountDownTimer的onFinish()里加上:
@Override public void onFinish() { Log.i("Finished!", "Heck Ya!"); theGraceCountDownTimer = null; // 执行完毕后释放引用 }
同理,第一个定时器执行完后也可以清空自身引用:
@Override public void onFinish() { Log.i("Timer One", "OnFinish"); theGraceCountDownTimer = new CountDownTimer(10000, 1000) { // 内部逻辑保持不变 }.start(); theFirstCountDownTimer = null; // 释放第一个定时器的引用 }
这样既能彻底解决空指针问题,也能减少潜在的内存泄漏风险~
内容的提问来源于stack exchange,提问作者Jackson Ennis
相关产品推荐
相关产品推荐

