在做Android客户端软件的时候经常需要刷新某区块内容,比如微博客户端就需要定期检测是否有新发布的微博内容,如果有新微博客户端就显示出来。Android里可以选用两种方式来实现此功能。
方式一、使用Timer(定时器)和TimerTask实现
示例代码:
public class MainActivity extends Activity {
private TextView msg;
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
update();
break;
}
super.handleMessage(msg);
}
void update() {
//刷新msg的内容
}
};
Timer timer = new Timer();
TimerTask task = new TimerTask() {
public void run() {
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
}
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
msg = (TextView) findViewById(R.id.txtMsg);
msg.setText("你好啊!");
timer.schedule(task, 1000 * 40, 1000 * 30); //启动timer
}
@Override
protected void onDestroy() {
if (timer != null) {// 停止timer
timer.cancel();
timer = null;
}
super.onDestroy();
}
}
方式二、使用Runnable和Handler
示例代码
public class MainActivity extends Activity {
private TextView msg;
private Handler handler = new Handler();
private Runnable runnable = new Runnable() {
public void run() {
this.update();
handler.postDelayed(this, 1000 * 120);// 间隔120秒
}
void update() {
//刷新msg的内容
}
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
msg = (TextView) findViewById(R.id.txtMsg);
msg.setText("你好啊!");
handler.postDelayed(runnable, 1000 * 60);
}
@Override
protected void onDestroy() {
handler.removeCallbacks(runnable); //停止刷新
super.onDestroy();
}
}
第一种方式还适用于消息通知的方式实现更新,第二种方式通常是主动去检查是否需要刷新。对于定时刷新这种使用第二种方式更
标签:界面,void,timer,handler,刷新,msg,new,定时,public From: https://blog.51cto.com/u_15070324/6088367