首页 > 代码库 > Handler

Handler

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

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

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

 

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();    
        
    }
}

 

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

 

 

 

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

 

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