如何让程序5秒钟更新一下Title.
首先我们看一下习惯了Java编程的人,在不知道Handler的用法之前是怎么样写的程序,代码如下所示:
package com.example.androidhandletest;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
private int title;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Timer timer=new Timer();
timer.scheduleAtFixedRate(new MyTask(), 1, 2000);
}
public class MyTask extends TimerTask {
@Override
public void run() {
// TODO Auto-generated method stub
Log.i("timer", "update...");
setTitle("update title : " + title);
title++;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
程序无法运行,所以Android 引进了Handler 这个特殊的类,可以说它是Runnable和Activity交互的桥梁
,所以我们只要在run方法中发送Message,而在Handler里,通过不同的Message执行不同的任务。
所以我们修改后的代码如下:
package com.example.androidhandletest;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
private int title;
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
//super.handleMessage(msg);
switch(msg.what){
case 1:
UpdateTile();
break;
}
}
};
private void UpdateTile() {
// TODO Auto-generated method stub
this.setTitle("update title : " + title);
title++;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Timer timer=new Timer();
timer.scheduleAtFixedRate(new MyTask(), 1, 2000);
}
public class MyTask extends TimerTask {
@Override
public void run() {
// TODO Auto-generated method stub
Log.i("timer", "update...");
Message msg=new Message();
msg.what=1;
handler.sendMessage(msg);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}