Toast为什么不可以在子线程里面运行

今天处理别人的程序的时候报错的地方一直是

new Thread(){
    public void run(){
        Toast.makeText(public_log.this,"图片不存在",Toast.LENGTH_SHORT).show();
    }
}

于是我深入了解,点击进入源码

  public static Toast makeText(Context context, CharSequence text, @Duration int duration) {
    Toast result = new Toast(context);

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

makeText方法好像没有什么不对,那么继续向下看show()方法

    public void show() {
    if (mNextView == null) {
        throw new RuntimeException("setView must have been called");
    }

    INotificationManager service = getService();
    String pkg = mContext.getOpPackageName();
    TN tn = mTN;
    tn.mNextView = mNextView;

    try {
        service.enqueueToast(pkg, tn, mDuration);
    } catch (RemoteException e) {
        // Empty
    }
}

好像没什么不对 但是看getService()不对劲就点击进去看一下

  static private INotificationManager getService() {
    if (sService != null) {
        return sService;
    }
    sService = INotificationManager.Stub.asInterface(ServiceManager.getService("notification"));
    return sService;
}

这里还是看不出有什么问题 然而show()里面这个又一次引起了我的注意

TN tn = mTN;

我点击进去查看源码,好家伙终于发现问题所在了

 private static class TN extends ITransientNotification.Stub {
    final Runnable mShow = new Runnable() {
        @Override
        public void run() {
            handleShow();
        }
    };

    final Runnable mHide = new Runnable() {
        @Override
        public void run() {
            handleHide();
            // Don't do this in handleHide() because it is also invoked by handleShow()
            mNextView = null;
        }
    };

    private final WindowManager.LayoutParams mParams = new WindowManager.LayoutParams();
    final Handler mHandler = new Handler();

    。。。。。代码省略。。。。。。


    /**
     * schedule handleShow into the right thread
     */
    @Override
    public void show() {
        if (localLOGV) Log.v(TAG, "SHOW: " + this);
        mHandler.post(mShow);
    }

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

    。。。。。代码省略。。。。。。
}

我相信聪明的你们应该看到了这里为什么错了,对,就是Handler不能再子线程里运行的 因为子线程没有创建Looper.prepare(); 所以就报错了。主线程不需要调用,是因为主线程已经默认帮你调用了。

可以看到一个Toast的创建需要依赖Handler。那么 我不要 我不要 我一定要在子线程使用Toast那怎么办。

其实很简单,它却什么就给它什么。

第一种方法

  new Thread(){
        @Override
        public void run() {
            super.run();
            Looper.prepare();
            try {
                Toast.makeText(MainActivity.this,"ceshi",Toast.LENGTH_SHORT).show();
            }catch (Exception e) {
                Logger.e("error",e.toString());
            }
            Looper.loop();
        }
    }.start();

因为除了Activity ui线程默认创建之外,其他线程不会自动创建调用 Looper.prepare()来给线程创建消息循环,然后再通过,Looper.loop()来使消息循环起作用。

第二种方法就是

  runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(MainActivity.this,"ceshi23333",Toast.LENGTH_SHORT).show();
        }
    });
    new Thread(){

    }.start();

Toast的代码创建在Runnable中,然后在需要Toast时,把这个Runnable对象传给runOnUiThread(Runnable)。 这样Runnable对像就能在ui程序中被调用。如果当前线程是UI线程,那么行动是立即执行

第三种方法和第一张差不多

  Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        //这里写你的Toast代码
        }
    };

    new Thread(){
        @Override
        public void run() {
            super.run();
            mHandler.sendEmptyMessage(0);
        }
    }.start();
  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值