6.4.2 postDelayed方法和removeCallbacks方法的使用(1)
方法postDelayed的作用是延迟多少毫秒后开始运行,而removeCallbacks方法是删除指定的Runnable对象,使线程对象停止运行。
方法声明如下:
- public final boolean postDelayed (Runnable r, long delayMillis)
其中参数Runnable r在Handler对象所运行的线程中执行。
创建名称为handler2的Android项目,Main.java的核心代码如下:
- public class Main extends Activity {
- private Button button1;
- private Button button2;
- private Handler handler = new Handler();
- private int count = 0;
- private Runnable runnableRef = new Runnable() {
- public void run() {
- Log.v("2", Thread.currentThread().getName());
- count++;
- Log.v("!", "count=" + count);
- handler.postDelayed(runnableRef, 1000);
- }
- };
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- Log.v("1", Thread.currentThread().getName());
- button1 = (Button) this.findViewById(R.id.button1);
- button2 = (Button) this.findViewById(R.id.button2);
- button1.setOnClickListener(new OnClickListener() {
- public void onClick(View arg0) {
- Thread thread = new Thread(runnableRef);
- thread.start();
- Log.v("!!!!!!!!!!!!!", "end");
- }
- });
- button2.setOnClickListener(new OnClickListener() {
- public void onClick(View arg0) {
- handler.removeCallbacks(runnableRef);
- }
- });
- }
- }
图6.41 循环加1效果 |
从打印结果可以发现,使用代码:
- handler.postDelayed(runnableRef, 1000)
上述代码运行的Runnable并没有新建一个线程,而是运行在main线程里。
当单击button2按钮时,停止这种累加1的功能。
关于循环执行某一个任务还可以使用Java SE自带的类来进行处理,新建名称为TimerTest项目,文件Main.java的代码如下:
- public class Main extends Activity {
- private int count = 0;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- TimerTask task = new TimerTask() {
- @Override
- public void run() {
- Log.v("!", "" + (++count));
- }
- };
- Timer timer = new Timer();
- timer.schedule(task, 1000, 1000);
- }
- }
图6.42 Timer循环执行某一任务 |