关于Toast不能在没有Looper的子线程使用

本文探讨了Android Toast不能在没有Looper的线程使用的原因,通过源码分析发现,Toast的显示涉及到NotificationManagerService和Binder机制。在makeText方法中传递的looper在show过程中用于线程切换,保证回调在正确的线程执行,这与AIDL和binder的线程模型有关。
摘要由CSDN通过智能技术生成

  Andorid中的Toast是一种比较常见的系统提示框。因为常见,所以常常忽略了其细节。经常使用的人都知道,Toast不能在没有Looper的线程显示提示框。那么下面通过源码来探究其原理。
  先来看看其makeText方法:

public static Toast makeText(Context context, CharSequence text, @Duration int duration) {
        return makeText(context, null, text, duration);
    }

public static Toast makeText(@NonNull Context context, @Nullable Looper looper,
            @NonNull CharSequence text, @Duration int duration) {
        Toast result = new Toast(context, looper);//创建对象

        LayoutInflater inflate = (LayoutInflater)
                context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflate.inflate(com.android.internal.R.layout.transient_notification, null);
        TextView tv = (TextView)v.findViewById(com.android.internal.R.id.message);
        tv.setText(text);

        result.mNextView = v;
        result.mDuration = duration;

        return result;
    }

  好像看不出来什么端倪。再来看看show方法:

public void show() {
        if (mNextView =
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值