码迷,mamicode.com
首页 > 移动开发 > 详细

Android笔记(三十三) Android中线程之间的通信(五)Thread、Handle、Looper和MessageQueue

时间:2015-09-18 22:00:02      阅读:244      评论:0      收藏:0      [点我收藏+]

标签:

ThreadLocal

         往下看之前,需要了解一下Java的ThreadLocal类,可参考博文:

         解密ThreadLocal

Looper、Handler和MessageQueue

       我们分析一下之前的这段代码,查看一下Handler机制中,Handle、Looper和MessageQueue之间到底是什么关系

package cn.lixyz.handlertest;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;


public class MainActivity extends Activity {

    private Button button;
    private Handler handler;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Message msg = handler.obtainMessage();
                msg.what = 100;
                handler.sendMessage(msg);
                Log.d("TTTT", "sendMessage:" + Thread.currentThread().getName());
            }
        });

        WorkerThread wt = new WorkerThread();
        wt.start();
    }


    class WorkerThread extends Thread {
        @Override
        public void run() {
            super.run();
            Looper.prepare();
            handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    Log.d("TTTT", "handleMessage:" + Thread.currentThread().getName());
                    int i = msg.what;
                    Log.d("TTTT", "收到了消息对象:" + i);
                    
                }
            };
            Looper.loop();
        }
    }
}

 

Android笔记(三十三) Android中线程之间的通信(五)Thread、Handle、Looper和MessageQueue

标签:

原文地址:http://www.cnblogs.com/xs104/p/4820398.html

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