码迷,mamicode.com
首页 > 其他好文 > 详细

Handler

时间:2014-05-21 19:29:29      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   c   code   java   

一、work线程向main线程发送数据(work线程发数据,main线程处理数据

bubuko.com,布布扣
public class MainActivity extends Activity {
   
    private Button button;
    private TextView textView;
    private Handler handler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button)this.findViewById(R.id.button1);
        textView = (TextView)this.findViewById(R.id.textView1);
handler
= new MyHandler(); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { new Thread(){ @Override public void run() { super.run(); Thread.currentThread().getName();//获取当前线程的名字 Message msg = Message.obtain(); String s = "hello handler"; msg.obj = s; handler.sendMessage(msg); } }.start(); } }); } public class MyHandler extends Handler{ @Override public void handleMessage(Message msg) { super.handleMessage(msg); String s = (String)msg.obj; textView.setText(s); } } }
bubuko.com,布布扣

 二、main线程向work线程发送数据(main线程发数据,work线程处理数据

 

bubuko.com,布布扣
public class MainActivity extends Activity {

    private Button button;
    private TextView textView;
    private Handler handler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button)this.findViewById(R.id.button);
        textView = (TextView)this.findViewById(R.id.textview);
        
        button.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                Message msg = Message.obtain();
                msg.obj = "handler2";
                handler.sendMessage(msg);
            }
        });
        new Thread(){

            @Override
            public void run() {
                super.run();
                Looper.prepare();//第一步
                handler = new Handler(){//第二步
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        String s = (String) msg.obj;
                        System.out.println(s);        
                    }
                    
                    
                };
                Looper.loop();//第三步
            }
        }.start();    
        
    }
}
bubuko.com,布布扣

 

三、Handler、Looper、MessageQueue的工作原理 

 

 

 

handler可以在任意线程发送消息

 

一个线程可以有多个Handler,但是只能有一个Looper!

 

Handler,布布扣,bubuko.com

Handler

标签:style   blog   class   c   code   java   

原文地址:http://www.cnblogs.com/stallran/p/3739825.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!