怎么定時(shí)刷新界面

在做Android客戶端軟件的時(shí)候經(jīng)常需要刷新某區(qū)塊內(nèi)容,比如微博客戶端就需要定期檢測(cè)是否有新發(fā)布的微博內(nèi)容,如果有新微博客戶端就顯示出來。Android里可以選用兩種方式來實(shí)現(xiàn)此功能。
方式一、使用Timer(定時(shí)器)和TimerTask實(shí)現(xiàn)
示例代碼:
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的內(nèi)容
}
};
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); //啟動(dòng)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的內(nèi)容
}
};
/
* 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();
}
}
第一種方式還適用于消息通知的方式實(shí)現(xiàn)更新,第二種方式通常是主動(dòng)去檢查是否需要刷新。對(duì)于定時(shí)刷新這種使用第二種方式更好

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容