有主線程發送message給子線程,主線程發送message
通常我們在處理耗時任務時候都會通過建立線程來處理,當任務處理完後通過Handler將結果發送回主線程。比如下面樣本:
1 package com.example.testlistener; 2 3 import java.util.Timer; 4 import java.util.TimerTask; 5 6 import android.app.Activity; 7 import android.content.res.Configuration; 8 import android.os.Bundle; 9 import android.os.Handler;10 import android.os.Message;11 import android.view.View;12 import android.view.View.OnClickListener;13 import android.view.View.OnLongClickListener;14 import android.widget.Button;15 import android.widget.EditText;16 import android.widget.Toast;17 18 public class MainActivity extends Activity {19 EditText txt;20 final Handler hander = new Handler(){21 public void handleMessage(android.os.Message msg) {22 if(msg.what == 0x1234){23 Toast.makeText(MainActivity.this, msg.arg1 + "", 1000).show();24 }25 };26 };27 @Override28 protected void onCreate(Bundle savedInstanceState) {29 super.onCreate(savedInstanceState);30 setContentView(R.layout.activity_main);31 32 new Timer().schedule(new TimerTask() {33 int i = 0;34 @Override35 public void run() {36 i++;37 Message msg = new Message();38 msg.what = 0x1234;39 msg.arg1 = i;40 hander.sendMessage(msg);41 }42 }, 0, 2000);43 }44 45 }
那麼,我們能不能通過Handler從主線程發送訊息給子線程呢?答案是肯定的,需要用到Looper.prepare()和Looper.loop()。如下面的代碼:
1 public class MainActivity extends Activity { 2 EditText txt; 3 Button bt; 4 TestThread testThread; 5 int j = 0; 6 7 @Override 8 protected void onCreate(Bundle savedInstanceState) { 9 super.onCreate(savedInstanceState);10 setContentView(R.layout.activity_main);11 txt = (EditText) findViewById(R.id.txt);12 bt = (Button) findViewById(R.id.bn);13 testThread = new TestThread();14 testThread.start();15 bt.setOnClickListener(new OnClickListener() {16 17 @Override18 public void onClick(View arg0) {19 j++;20 Message msg = new Message();21 msg.what = 0x1000;22 msg.arg1 = j;23 testThread.thander.sendMessage(msg);24 }25 });26 27 28 }29 30 //自訂子線程31 class TestThread extends Thread{32 public Handler thander;33 @Override34 public void run() {35 //建立一個Looper對象36 Looper.prepare();37 thander = new Handler(){38 @Override39 public void handleMessage(Message msg) {40 if(msg.what == 0x1000){41 System.out.println("j = " + msg.arg1);42 //txt.setText(msg.arg1 + "");43 }44 }45 };46 //啟動Looper47 Looper.loop();48 }49 }50 51 }