写惯java的人可能会认为Timer的使用应该如下:
程序功能很简单:10秒后,SetTitle为“hear me?”,然后,实际上这样做是不行的,这跟Android的线程安全有关!
- package com.ray.test;
- import java.util.Timer;
- import java.util.TimerTask;
- import android.app.Activity;
- import android.os.Bundle;
- public class JavaTimer extends Activity {
- Timer timer = new Timer();
- TimerTask task = new TimerTask(){
- public void run() {
- setTitle("hear me?");
- }
- };
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- timer.schedule(task, 10000);
- }
- }
但实际上的用法应该通过配合Handler来实现timer功能的!
- package com.ray.test;
- import java.util.Timer;
- import java.util.TimerTask;
- import android.app.Activity;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.Message;
- public class TestTimer extends Activity {
- Timer timer = new Timer();
- Handler handler = new Handler(){
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case 1:
- setTitle("hear me?");
- break;
- }
- super.handleMessage(msg);
- }
- };
- TimerTask task = new TimerTask(){
- public void run() {
- Message message = new Message();
- message.what = 1;
- handler.sendMessage(message);
- }
- };
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- timer.schedule(task, 10000);
- }
- }
- 1楼ihrthk3天前 19:18
- 干嘛还要用Timer啊,直接用Handler呗
- Re: chang_xing3天前 20:10
- 回复ihrthknTimer和Timertask结合可以很好的控制消息的传递呀。n请问有什么想法可以分享吗?(代码)
- Re: ihrthk3天前 22:11
- 回复chang_xingn看这个例子,Timer的作用就是异步+延时,Handler本身也是有的。
- Re: chang_xing3天前 08:25
- 回复ihrthkn不用Timer要再写个线程吗?朋友可以分享个小例子吗?(例子链接也可以)
- Re: ihrthk3天前 08:43
- 回复chang_xingnhandler.postAtTime(new Runnable(){nn @Overriden public void run() {n // TODO Auto-generated method stubn setTitle("hear me?"); n }n n }, 10000);
- Re: chang_xing3天前 10:39
- 回复ihrthknhttp://blog.csdn.net/chang_xing/article/details/7829653
- Re: chang_xing3天前 10:44
- 回复ihrthkn懂了,还是实现了Runnable()接口。下面是一个秒表的例子,没用Timer