在
android
平台中多線程應用很廣泛,在
ui
更新、遊戲開發和耗時處理(網絡通信等)等方面都需要多線程。
線程涉及到的技術有:
handler,
message,messagequeue,looper,handlerthread。
public void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
setcontentview(r.layout.main);
btnend = (button) findviewbyid(r.id.btnend);
btnend.setonclicklistener(new onclicklistener() {
@override
public void onclick(view v) {
isrunning = false;
}
});
labeltimer = (textview) findviewbyid(r.id.labeltimer);
handlerthread thread = new
handlerthread("myhandlerthread");
thread.start();
handler = new handler(thread.getlooper());
runnable r = new runnable() {
public void run() {
if (isrunning) {
labeltimer.settext("
逝去了
" +timer + "
秒
");
timer++;
handler.postdelayed(this,
1000);
};
handler.postdelayed(r, 1000);
用
new
handlerthread("myhandlerthread")
建立
handlerthread
線程,通過
thread.start()
方法啟動該線程。
的
getlooper()
方法可以獲得與
線程對象關聯的
looper
對象。再用
對象建構
new handler(looper)
。