can't create handler inside thread that has not called Looper.prepare

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/MitKey/article/details/53958664
出现原因:不是在主线程(UI线程)中

demo

下面的代码会抛出如题的异常信息

new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            // 模拟耗时操作
            Thread.sleep(1000 * 2);

            Toast.makeText(getApplicationContext(), "下载成功", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});

常用解决办法

  1. 使用 android.os.Handler
  2. 使用 android.app.Activity 类的 public final void android.app.Activity.runOnUiThread(Runnable action) 方法

猜你喜欢

转载自blog.csdn.net/MitKey/article/details/53958664