class="aTitle" style="text-align: center">handler消息机制入门

1 package com.example.handlerrumen;
2
3 import android.app.Activity;
4 import android.os.Bundle;
5 import android.os.Handler;
6 import android.os.Looper;
7 import android.os.Message;
8 import android.util.Log;
9 import android.widget.TextView;
10
11 public class MainActivity extends Activity {
12 private TextView tv_txt;
13 private Handler handler=new Handler(){
14 //处理消息(被主线程执行)
15 public void handleMessage(Message msg) {
16 String str=(String) msg.obj;
17 tv_txt.setText(str);
18
19 //判断当前函数是否被主线程调用的方式
20 // boolean result=Looper.getMainLooper()==Looper.myLooper();
21 // Log.d("bh",result+"");
22 };
23 };
24 @Override
25 protected void onCreate(Bundle savedInstanceState) {
26 super.onCreate(savedInstanceState);
27 setContentView(R.layout.activity_main);
28 tv_txt=(TextView) findViewById(R.id.tv_txt);
29 //创建子线程,并启动
30 MyThread myTh=new MyThread();
31 myTh.start();
32 }
33 //自定义子线程
34 class MyThread extends Thread{
35 @Override
36 public void run() {
37 //伪代码来体现
38 try {
39 Thread.sleep(6000);
40 Log.d("bh","访问到网络了");
41 String str="我是网络数据";
42 //创建message对象
43 Message msg=new Message();
44 msg.obj=str;
45 //发送一个消息
46 handler.sendMessage(msg);
47 } catch (InterruptedException e) {
48 e.printStackTrace();
49 }
50 }
51 }
52 }