Android Toast机制实现原理

Toast的实现原理

通过本文,你将懂得:
1. 为什么调用Toast的子线程需要Looper.prepare()
2. Toast的Window是在哪里创建的

Toast中的IPC通信

在Toast的实现中主要有两类IPC通信:
1. 从Toast通过IPC访问NotificationManagerService(以下简称NMS)
2. 从NMS通过IPC访问Toast

其中,Toast通过SystemServer来获取NMS的远程代理对象;NMS通过Toast传递过来的远程代理对象TN来进行IPC。

TN类 典型的AIDL生成的IBinder服务端Stub类。

private static class TN extends ITransientNotification.Stub {
   
    /**
         * schedule handleShow into the right thread
         */
        @Override
        public void show(IBinder windowToken) {
            if (localLOGV) Log.v(TAG, "SHOW: " + this);
            mHandler.obtainMessage(0, windowToken).sendToTarget();
        }

        /**
         * schedule handleHide into the right thread
         */
        @Override
        public void hide() {
            if (localLOGV) Log.v(TAG, "HIDE: " + this);
            mHandler.post(mHide);
        }
}

NotificationManagerService 是通过ToastRecord中的callback来回调TN中的方法的,实际上callback就是TN在客户端中的类。

private static final class ToastRecord
{
   
        final int pid;
        final String pkg;
        final ITransientNotification callback;
        int duration;
        Binder token;
}

源码分析

从Toast类的show()方法开始:

    public void show() {
        if (mNextView == null) {
            throw new RuntimeException("setView must have been called");
        }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值