Android开发

Toast不能直接在子线程中使用

2018-07-10  本文已影响421人  Winterfell_Z
new Thread(){
    public void run(){
        Toast.makeText(public_log.this,"图片不存在",Toast.LENGTH_SHORT).show();
    }
}

如果像这样直接在子线程中弹出Toast,程序会报错。

深入源码了解一下原因:

  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();

另:在非主线程中直接new Handler() 会报如下的错误: E/AndroidRuntime( 6173): Uncaught handler: thread Thread-8 exiting due to uncaught exception E/AndroidRuntime( 6173): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() 原因是非主线程中默认没有创建Looper对象,需要先调用Looper.prepare()启用Looper。

上一篇下一篇

猜你喜欢

热点阅读