在主UI線程中,系統已經初始化了一個Looper對象,因此程序直接創建Handler即可,然後公告handler來發送消息,處理消息。
程序猿自己啓動的子線程,程序猿必須自己創建一個Looper對象,並且啓動它,創建looper對象調用他的prepare()方法即可。該方法
保證每一個線程最多隻有一個Lopper對象
調用Looper的prepare()方法爲當前線程創建Looper對象,創建Looper對象的時候,他的構造器會創建一個與之配套的MessageQueue
調用Looper的loop()方法啓動Lopper.
如下爲用新線程計算質數例子
public class MainActivity extends Activity {
private EditText et;
private Button bt;
private TextView tv;
static final String UPPER_NUM = "upper";
calThread calthread;
class calThread extends Thread {
public Handler mhandler;
@Override
public void run() {
Looper.prepare();
mhandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 0x123) {
int upper = msg.getData().getInt(UPPER_NUM);
List<Integer> nums = new ArrayList<Integer>();
outer: for (int i = 2; i <= upper; i++) {
for (int j = 2; j <= Math.sqrt(i); j++) {
if (i != 2 && i % j == 0) {
continue outer;
}
}
nums.add(i);
}
Toast.makeText(MainActivity.this, nums.toString(),
Toast.LENGTH_SHORT).show();
}
}
};
Looper.loop();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.editText1);
bt = (Button) findViewById(R.id.button1);
tv = (TextView) findViewById(R.id.textView1);
calthread = new calThread();
calthread.start();
bt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Message ms = new Message();
ms.what = 0x123;
Bundle bundle = new Bundle();
bundle.putInt(UPPER_NUM, Integer.parseInt(et.getText().toString()));
ms.setData(bundle);
calthread.mhandler.sendMessage(ms);
}
});
}
}