在Android中,activity做为主线程,如其他线程需要与其交互,要在message队列中进行处理。至于Handler、Message、MessageQueue、looper在网上都有很多详细说明,讲的也就是将消息或线程通过handler放入消息队列,looper用于消息队列中就行消息间的通信,在消息队列的尾部,通过Handler来取出消息进行处理,即handlermessage()方法,采用的是先进先出的方式处理消息,可以参考下这个链接:http://www.linuxidc.com/Linux/2011-08/40055.htm下面是自己写的一个小例子:
- public class HandlerTest1 extends Activity {
- /** Called when the activity is first created. */
- private TextView text = null;
- private Button but1 = null;
- private Button but2 = null;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- text = (TextView) findViewById(R.id.text);
- but1 = (Button) findViewById(R.id.but1);
- but2 = (Button) findViewById(R.id.but2);
- but1.setOnClickListener(new OnClickListener(){
-
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- handler.post(r); //将线程加入到消息队列中
- }
-
- });
- but2.setOnClickListener(new OnClickListener(){
-
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- handler.removeCallbacks(r); //清空消息队列
- }
-
- });
- }
- Handler handler = new Handler(){
-
- @Override
- public void handleMessage(Message msg) {
- // TODO Auto-generated method stub
- text.setText(String.valueOf(msg.arg1));
- System.out.println(msg.arg1);
- handler.postDelayed(r, 2000); //将线程重新加入到消息队列中,产生一种循环
-
- }
-
- };
-
- Runnable r = new Runnable(){
- int i = 0;
- @Override
- public void run() {
- // TODO Auto-generated method stub
- System.out.println("runnable");
- Message msg = handler.obtainMessage(); //获得message对象
- msg.arg1=i; //arg1,arg2 ,bunder,obj等作为消息传递数据
- i++;
- handler.sendMessage(msg); //发送消息
- }
-
- };
-
-
- }
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <TextView
- android:id="@+id/text"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="hello"
- />
- <Button
- android:id="@+id/but1"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="开始"
- />
- <Button
- android:id="@+id/but2"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="结束"
- />
- </LinearLayout>