當前位置:編程學習大全網 - 編程語言 - Oncreate編程

Oncreate編程

您不能在子線程中更新UI。這是我之前寫的壹個例子。聽著,使用處理程序消息機制。

公共類HandlerDemoActivity擴展Activity實現OnClickListener {

按鈕btn1,btn2

ProgressBar progressBar

updatedata handler updatedata handler;

HandlerThread handlerThread

/**首次創建活動時調用。*/

@覆蓋

public void on create(Bundle saved instancestate){

super . oncreate(savedInstanceState);

setContentView(r . layout . main);

BTN 1 =(Button)findViewById(r . id . BTN 1);

Bt N2 =(Button)findViewById(r . id . Bt N2);

progress bar =(progress bar)findViewById(r . id . progress bar 1);

btn1.setOnClickListener(這個);

Bt N2 . setonclicklistener(this);

}

/**

*自定義壹個類繼承Handler類,重寫handleMessage函數。

*並且需要壹個帶有Looper對象的構造函數。

*循環檢測是否有消息。如果有消息,將調用handleMessage來檢索數據。

*如果沒有消息,進入等待狀態。

* @作者管理員

*

*/

類UpdateDataHandler擴展處理程序{

public update data handler(Looper Looper){

超級(looper);

}

@覆蓋

公共void handleMessage(Message msg) {

super . handle message(msg);

system . out . println("-"+thread . current thread()。getId());

progress bar . set progress(msg . arg 1);//從消息隊列中獲取數據並更新控件。

updatedatahandler . post(print runnable);

}

}

runnable print runnable = newrunnable(){//實現壹個線程類。

int I = 0;

@覆蓋

Public void run() {//重寫線程類中的run函數。

I+= 20;

message msg = updatedata handler . obtain message();//獲取處理程序的消息對象。

msg . arg 1 = I;//將數據放入消息對象。

//msg . obj = obj;//也可以發送壹些對象。

//msg . setdata();//可以發送壹個Bundle對象。

嘗試{

thread . sleep(1000);//暫停1秒

} catch (InterruptedException e) {

e . printstacktrace();

}

system . out . println(I);

如果(i & gt100) //判斷當變量達到100時,運算結束。

{

updatedatahandler . remove callbacks(print runnable);//從處理程序中釋放線程類

返回;

}

//msg . sendtotarget();//這個函數也可以用來發送消息。

updatedata handler . sendmessage(msg);//將消息對象放入消息隊列。

}

};

@覆蓋

公共void onClick(視圖v) {

if(v == btn1)

{

handler thread = new handler thread(" ");// HandlerThread是壹個線程,繼承自Thread。它保存了對Looper實例的引用。

handler thread . start();//壹定要調用線程的啟動函數。

updatedata handler = new updatedata handler(handler thread . get looper());

updatedatahandler . post(print runnable);

System.out.println("主線程"+Thread.currentThread()。getId());

}

}

}

  • 上一篇:論述影響車銑復合機床加工精度的因素有哪些
  • 下一篇:畢業設計論文總結報告
  • copyright 2024編程學習大全網