Chinaunix首页 | 论坛 | 博客
  • 博客访问: 838806
  • 博文数量: 182
  • 博客积分: 1992
  • 博客等级: 上尉
  • 技术积分: 1766
  • 用 户 组: 普通用户
  • 注册时间: 2010-10-18 11:49
文章分类

全部博文(182)

文章存档

2019年(1)

2016年(5)

2015年(29)

2014年(38)

2013年(21)

2012年(36)

2011年(52)

我的朋友

分类: Android平台

2014-02-21 16:23:32

一值总觉得timer怪怪的,就是不知道怎么解释,这个解释正到好处。

TimerTasks are not ideal to use in an android environment because they're not context-aware. If your context goes away, the TimerTask will still wait patiently in the background, eventually firing and potentially crashing your app because its activity was previously finished. Or, it may keep references to your activity around after it's been closed, preventing it from being garbage collected and potentially making your app run out of memory.

Instead, use postDelayed(), which will automatically cancel the task when the activity is shut down.

final int delay = 5000; final int period = 1000; final Runnable r = new Runnable() { public void run() { Toast.makeText(getApplicationContext(),"RUN!",Toast.LENGTH_SHORT).show(); postDelayed(this, period); } }; postDelayed(r, delay);

By the way, if you ever need to cancel your task manually, you can use removeCallbacks(r) where r is the runnable you posted previously

阅读(2013) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~