转 在子线程中new Handler报错--Can't create handler inside thread that has not called Looper.prepare()

在子线程中new一个Handler为什么会报以下错误?

java.lang.RuntimeException: 

Can‘t create handler inside thread that has not called Looper.prepare() 

这是因为Handler对象与其调用者在同一线程中,如果在Handler中设置了延时操作,则调用线程也会堵塞。每个Handler对象都会绑定一个Looper对象,每个Looper对象对应一个消息队列(MessageQueue)。如果在创建Handler时不指定与其绑定的Looper对象,系统默认会将当前线程的Looper绑定到该Handler上。
在主线程中,可以直接使用new Handler()创建Handler对象,其将自动与主线程的Looper对象绑定;在非主线程中直接这样创建Handler则会报错,因为Android系统默认情况下非主线程中没有开启Looper,而Handler对象必须绑定Looper对象。这种情况下,则有两种方法可以解决此问题:

方法1:需先在该线程中手动开启Looper(Looper.prepare()-->Looper.loop()),然后将其绑定到Handler对象上;

final Runnable runnable = new Runnable() {
  @Override
  public void run() {
    //执行耗时操作
    try {

      Log.e("bm", "runnable线程: " + Thread.currentThread().getId()+ " name:" + Thread.currentThread().getName());

      Thread.sleep(2000);
      Log.e("bm", "执行完耗时操作了~");
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
  }
};
new Thread() {
  public void run() {
    Looper.prepare();
    new Handler().post(runnable);//在子线程中直接去new 一个handler
    Looper.loop();    //这种情况下,Runnable对象是运行在子线程中的,可以进行联网操作,但是不能更新UI
  }
}.start();

方法2:通过Looper.getMainLooper(),获得主线程的Looper,将其绑定到此Handler对象上。

final Runnable runnable = new Runnable() {
  @Override
  public void run() {
    //执行耗时操作
    try {

      Log.e("bm", "runnable线程: " + Thread.currentThread().getId()+ " name:" + Thread.currentThread().getName());
      Thread.sleep(2000);
      Log.e("bm", "执行完耗时操作了~");
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
  }
};
new Thread() {
  public void run() {
    new Handler(Looper.getMainLooper()).post(runnable);//在子线程中直接去new 一个handler

    //这种情况下,Runnable对象是运行在主线程中的,不可以进行联网操作,但是可以更新UI
  }
}.start();

转 在子线程中new Handler报错--Can't create handler inside thread that has not called Looper.prepare()

原文地址:https://www.cnblogs.com/Jerseyblog/p/8932472.html

时间: 2025-01-18 11:05:42

转 在子线程中new Handler报错--Can't create handler inside thread that has not called Looper.prepare()的相关文章

[转载] python在子线程中使用WMI报错

本文转载自: http://www.68idc.cn/help/jiabenmake/python/20150123184163.html 我在一个python脚本中用到了WMI,用于确保杀死超时却未能自己结束的进程 (已经先尝试了Ctrl+Break中止). 测试代码运行正常,但当我把这个函数放在子线程中使用时,却发现报错: com_error: (-2147221020, 'Invalid syntax', None, None) 后来在网上检索,发现必须添加初始化函数和去初始化函数,所以在

关于子线程使用Toast报错Can't create handler inside thread that has not called Looper.prepare()的解决办法

形同如下代码,在Thread中调用Toast显示错误信息: new Thread(new Runnable(){ @Override public void run() { try{ weatherData = getWeatherData(strUrl); parseJson(weatherData); }catch(Exception e){ Toast.makeText(WindowApplication.getAppContext(), e.toString(), Toast.LENGT

Android 线程更新UI报错 : Can't create handler inside thread that has not called Looper.prepare()

MainActivity中有一个按钮,绑定了save方法 public void save(View view) { String title = titleText.getText().toString(); String timelength = lengthText.getText().toString(); ExecutorService exec = Executors.newCachedThreadPool(); exec.execute(new NewsService(getApp

Android handler 报错处理Can't create handler inside thread that has not called Looper.prepare()

解决方法,在ui线程里面创建handler m_MainActivity.runOnUiThread(new Runnable(){ @Override public void run() { // TODO Auto-generated method stub GameBoxUtil.startPay(m_MainActivity,String.valueOf(amount), productName, payCode,orderId,payHandler); }}); Android han

Android蓝牙开发,报BluetoothAdapter﹕ Can't create handler inside thread that has not called Looper.prepare

这个错误翻译的意思是:不能在没有Looper.prepare的线程里面创建handler. 起初我很疑惑,我根本没有用到工作线程,也没有创建handler.报错的代码如下: // Device scan callback. private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() { @Override public void onLeScan(final Blu

使用okhttp 报Can't create handler inside thread that has not called Looper.prepare()

我是在用okhttp的请求数据,在处理数据的时候,打开了一个dialog用来提示,然后报了这个错误. 经过调试,发现错误原因是: dialog必须在一个被Looper.prepare()回调的的线程里创建,但是okhttp这个线程不具备这个条件 <span style="font-size:14px;">OkHttpUtil.getDataInGet(updateUrl, new Callback() { @Override public void onFailure(Re

Can&#39;t create handler inside thread that has not called Looper.prepare()

最近做项目时出现个问题. 在一个基类中,创建一个Handler对象用于主线程向子线程发送数据,代码如下: this.mThirdHandler = new Handler(){ @Override public void handleMessage(android.os.Message msg) { super.handleMessage(msg); Bundle bundle = msg.getData(); isStop = bundle.getBoolean(mContext.getTex

解决使用Handler时Can&#39;t create handler inside thread that has not called Looper.prepare()

在android开发中,主线程不能进行耗时操作,所以我们经常把耗时操作放在子线程中进行,那么就需要子线程与主线程相互交流,就需要使用到handler. 而在使用handler过程中,如果对handler使用不太熟练的话就偶尔会出现Can't create handler inside thread that has not called Looper.prepare()的报错异常.之前在Handler的原理的博文中有讲到,Handler的使用会依靠Looper循环来发送消息,如果不创建Loope

java.lang.RuntimeException: Can&#39;t create handler inside thread that has not called Looper.prepare()

1. 程序时,出现运行时异常,如上图所示. 2.异常原因分析.在ContentObserver的onChange方法中,调用了Toast.makeText方法.onChange方法应该在子线程运行,在android中的子线程中不能直接控制UI组件,否则就会报异常 3.Looper类别用来为一个线程开启一个消息循环.默认情况下Android中新诞生的线程是没有开启消息循环的.(主线程除外,主线程系统会自动为其创建Looper对象,开启消息循环) java.lang.RuntimeException