在主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);
}
});
}
}