Android开发系列七:怎么定时刷新界面
1个回答
2016-11-14 · 百度知道合伙人官方认证企业
育知同创教育
1【专注:Python+人工智能|Java大数据|HTML5培训】 2【免费提供名师直播课堂、公开课及视频教程】 3【地址:北京市昌平区三旗百汇物美大卖场2层,微信公众号:yuzhitc】
向TA提问
关注
展开全部
方法:使用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();
}
}
参考代码:
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();
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询