在子線程中new Handler報(bào)錯(cuò)--Can't create handler inside thread that has not called Looper.prepare()

在子線程中new一個(gè)Handler為什么會(huì)報(bào)以下錯(cuò)誤?

java.lang.RuntimeException: 

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

這是因?yàn)镠andler對(duì)象與其調(diào)用者在同一線程中,如果在Handler中設(shè)置了延時(shí)操作,則調(diào)用線程也會(huì)堵塞。每個(gè)Handler對(duì)象都會(huì)綁定一個(gè)Looper對(duì)象,每個(gè)Looper對(duì)象對(duì)應(yīng)一個(gè)消息隊(duì)列(MessageQueue)。如果在創(chuàng)建Handler時(shí)不指定與其綁定的Looper對(duì)象,系統(tǒng)默認(rèn)會(huì)將當(dāng)前線程的Looper綁定到該Handler上。
在主線程中,可以直接使用new Handler()創(chuàng)建Handler對(duì)象,其將自動(dòng)與主線程的Looper對(duì)象綁定;在非主線程中直接這樣創(chuàng)建Handler則會(huì)報(bào)錯(cuò),因?yàn)锳ndroid系統(tǒng)默認(rèn)情況下非主線程中沒有開啟Looper,而Handler對(duì)象必須綁定Looper對(duì)象。這種情況下,則有兩種方法可以解決此問題:

方法1:需先在該線程中手動(dòng)開啟Looper(Looper.prepare()-->Looper.loop()),然后將其綁定到Handler對(duì)象上;

final Runnable runnable = new Runnable() {
  @Override
  public void run() {
    //執(zhí)行耗時(shí)操作
    try {

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

      Thread.sleep(2000);
      Log.e("bm", "執(zhí)行完耗時(shí)操作了~");
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
  }
};
new Thread() {
  public void run() {
    Looper.prepare();
    new Handler().post(runnable);//在子線程中直接去new 一個(gè)handler
    Looper.loop();    //這種情況下,Runnable對(duì)象是運(yùn)行在子線程中的,可以進(jìn)行聯(lián)網(wǎng)操作,但是不能更新UI
  }
}.start();

方法2:通過Looper.getMainLooper(),獲得主線程的Looper,將其綁定到此Handler對(duì)象上。

final Runnable runnable = new Runnable() {
  @Override
  public void run() {
    //執(zhí)行耗時(shí)操作
    try {

      Log.e("bm", "runnable線程: " + Thread.currentThread().getId()+ " name:" + Thread.currentThread().getName());
      Thread.sleep(2000);
      Log.e("bm", "執(zhí)行完耗時(shí)操作了~");
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
  }
};
new Thread() {
  public void run() {
    new Handler(Looper.getMainLooper()).post(runnable);//在子線程中直接去new 一個(gè)handler

    //這種情況下,Runnable對(duì)象是運(yùn)行在主線程中的,不可以進(jìn)行聯(lián)網(wǎng)操作,但是可以更新UI
  }
}.start();

原文: https://www.cnblogs.com/jingmo0319/p/5730963.html

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容