上一篇文章中,示範了在一個WorkerThread當中如何向MainThread丟data的方法,此篇將延續上一篇,接著示範如何從MainThread將data傳向WorkerThread中。
以下為MainThread to WorkerThread的範例,其範例為點擊Button1時,將MainThread的Data丟到WorkerThread:
首先建立物件 textview1、button1、handler1
private TextView textview1;
private Button button1; //點擊button1後,將建立一個消息對象msg=handler1.obtainMessage()
private Handler handler1;
在onCreat將各元件綁定各ID,再將Button1綁定 button1clicklistener()
接著生成一個t線程,其線程使用的方法為MyThread(),再使用start()啟動該線程。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview1=(TextView)findViewById(R.id.tv1ID);
button1=(Button)findViewById(R.id.btn1ID);
button1.setOnClickListener(new button1clicklistener());
Thread t=new MyThread(); //建立一個Thread t綁MyThread()
t.start();//t程序開始
}
當點擊Button1後,將建立一個消息對象msg,其msg獲取的消息對象為 handler1
接著將data 1存到 msg,再透過handler1.sendMessage(msg)將data傳到消息對列當中
class button1clicklistener implements View.OnClickListener{
@Override
public void onClick(View v) {
Message msg=handler1.obtainMessage();//點擊Button1後,建立一個消息對象為handler1。
msg.what=1; //將數字1存到msg當中
handler1.sendMessage(msg); //將msg送到消息對列
}
}
以下為一個WorkerThread,其中可以發現Handler是直接建立在WorkerThread中,並使用Looper不斷地循環偵測消息對列中是否有data,接著再將消息對列中的msg內的data抓出來存到
int a中,並使用System.out.println()打印出剛剛所抓出來的data,可以再IDE介面看到每當點擊一次Button1時,debug視窗會打印出 1。
//WorkerThread
class MyThread extends Thread{ //該WorkerThread中建立一個不斷循環地Looper,並在該線程生成一個Handler,
@Override
public void run(){
//準備Looper對象
Looper.prepare();
//在WorkerThread中生成一個Handler對象
handler1=new Handler(){
@Override
public void handleMessage(Message msg){
int a=msg.what;
System.out.println("thread:"+currentThread().getName());
System.out.println(a+"");
}
};
//調用Looper.loop(),Looper對象將不斷從消息對列中取出消息對象,然後調用handler的handleMessage,處理該消息對象
// 如果消息對列中沒有對象,則該Thread阻塞,
Looper.loop();
}
}
以上為MainThread向WorkerThread丟data的範例。
可以發現到範例中的Handler是直接建立在WorkerThread中,並使用Looper不斷地偵測消息對列中是否有儲存新的msg。