android 中handler的用法分析

本文深入解析了Android中Handler机制的工作原理,包括如何在UI线程和非UI线程中使用Handler发送消息,Looper与MessageQueue的关系,以及如何通过Handler实现跨线程的UI更新。

1、直接再ui线程中初始化,这种情况handlermessage会在 ui线程中执行

2、传入Looper 参数,这种情况会在ht线程中执行 handlermessage。

HandlerThread ht = new HandlerThread("handler");
ht.start();
Handler handler = new Handler(ht.getLooper());

步骤分析:

1、HandlerThread 继承Thread

 public void run() {
        mTid = Process.myTid();
        Looper.prepare();
        synchronized (this) {
            mLooper = Looper.myLooper();
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        Looper.loop();
        mTid = -1;
    }

2、在run 分别初始化 ,绑定Looper 到当前线程,并且执行looper 循环处理MessageQuene 中的message

//初始化Looper
a) Looper.prepare(); b) if (sThreadLocal.get() != null) { throw new RuntimeException("Only one Looper may be created per thread"); } sThreadLocal.set(new Looper()); c) private Looper() { mQueue = new MessageQueue(); mRun = true; mThread = Thread.currentThread(); } //绑定 Looper 到当前线程 a) sThreadLocal.set(new Looper()); b) public void set(T value) { Thread currentThread = Thread.currentThread(); //取出当前线程中的ThreadLocal.Values变量 Values values = values(currentThread); if (values == null) { values = initializeValues(currentThread); } //将Looper变量保存到ThreadLocal.Values 变量中 values.put(this, value); } c) Values values(Thread current) { return current.localValues; } //循环处理Message Looper.looper()

所以线程ht.getLooper() 可以用 ThreadLocal 从 当前线程中获取 Looper

3 、Handler 中的MessageQuene 为 Looper中 MessageQuene 的引用 ,sendmessage将Message保存到 MessageQuene,然后 再loop中取用。

public boolean sendMessageAtTime(Message msg, long uptimeMillis)
    {
        boolean sent = false;
        MessageQueue queue = mQueue;
        if (queue != null) {
            msg.target = this;
            sent = queue.enqueueMessage(msg, uptimeMillis);
        }
        else {
            RuntimeException e = new RuntimeException(
                this + " sendMessageAtTime() called with no mQueue");
            Log.w("Looper", e.getMessage(), e);
        }
        return sent;
    }

 Handler 另外用法 在service(或者非UI线程)中调用Toast等UI操作

looper = Looper.getMainLooper();
handler = new Handler(looper);
handler.post(new Runnable()
{
   public void run()
   {
       Toast.makeText().show();  
   }
});

同样可以使用Activity.runOnUiThread(Runnable r);

转载于:https://www.cnblogs.com/lipeil/archive/2012/07/31/2617012.html

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值