Android中timer(计时器)的使用

来源:互联网 发布:网络监察大队 编辑:程序博客网 时间:2024/05/01 18:39

主要步骤是:

在TimerTask的子线程中发送消息个handler,handler负责ui线程的改变

                        timer用于执行TimerTask子线程;

项目结构:




MainActivity :

public class MainActivity extends Activity {



private TextView tv;
private Button bt;
Timer timer=null;


// 定义Handler
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
// handler处理消息
if (msg.what > 0) {
tv.setText(" " + msg.what);
} else {
// 在handler里可以更改UI组件
tv.setText("开始点火");
timer.cancel();// 退出计时器
}
}


};


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 定义UI组件
tv = (TextView) findViewById(R.id.textView1);
bt = (Button) findViewById(R.id.bt);


// 定义按钮的点击监听器
bt.setOnClickListener(new OnClickListener() {


@Override
public void onClick(View v) {
TimerTask task = new TimerTask() {
int i = 10;


public void run() {
   //定义一个消息传过去
Message message = new Message();
message.what = i--;
handler.sendMessage(message);
}
};
   timer = new Timer(true);
timer.schedule(task, 1000, 1000); // 延时1000ms后执行,1000ms执行一次


}
}
);



}


}//class

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >


    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    
    <Button 
        android:id="@+id/bt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        
        
        />



    


</LinearLayout>

如果没有明白下载我的例子

http://download.csdn.net/detail/zhaihaohao1/8389193



0 0
原创粉丝点击