Android

java.lang.RuntimeException: Can’t create handler inside thread Thread[Thread-4,5,main] that has not called Looper.prepare()

스레드 안에서 다이얼(Dialog)를 호출하면서 발생한 오류이다. 오류가 발생한 코드를 보면 문제가 없어보인다. 그러나 오류는 발생하였다.

new Thread(new Runnable() {
   @Override
    public void run() {
      try {
         Thread.sleep(2000);
      } catch (Throwable ex) {
         ex.printStackTrace();
      }
      CheckFCM(); //다이얼로그 호출
    }
}).start();

왜?

public void CheckFCM() {

  if (!IntroActivity.this.isFinishing()) {
   final Dialog personDialog = new Dialog(IntroActivity.this);


   personDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
   personDialog.setContentView(R.layout.dialog_bmi); 
   
   personDialog.getWindow().setBackgroundDrawable(new ColorDrawable(0)); 
   personDialog.setCancelable(false);
   Button bunConfirm = (Button) personDialog.findViewById(R.id.bunConfirm);
   
   bunConfirm.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
      if (v.getId() == R.id.bunConfirm) {
            if (!IntroActivity.this.isFinishing() && personDialog != null && personDialog.isShowing()) {
              personDialog.dismiss();
              CallMainActivity();
            }    
      }
   }
  });

   if (!IntroActivity.this.isFinishing() && personDialog != null && !personDialog.isShowing()) {
      personDialog.show();
   }
  }
 }

22088/com.Test W/System.err: java.lang.RuntimeException: Can’t create handler inside thread Thread[Thread-4,5,main] that has not called Looper.prepare()
2019-12-05 05:41:02.140 22032-22088/com.Test W/System.err:     at android.os.Handler.(Handler.java:207)
2019-12-05 05:41:02.140 22032-22088/com.Test W/System.err:     at android.os.Handler.(Handler.java:119)
2019-12-05 05:41:02.140 22032-22088/com.Test W/System.err:     at android.app.Dialog.(Dialog.java:133)
2019-12-05 05:41:02.140 22032-22088/com.Test W/System.err:     at android.app.Dialog.(Dialog.java:162)
2019-12-05 05:41:02.140 22032-22088/com.Test W/System.err:     at com.Test.IntroActivity.setHeightandWeight(IntroActivity.java:62)
2019-12-05 05:41:02.140 22032-22088/com.Test W/System.err:     at com.Test.IntroActivity.CheckFCM(IntroActivity.java:310)
2019-12-05 05:41:02.140 22032-22088/com.Test W/System.err:     at com.Test.IntroActivity$1.run(IntroActivity.java:53)
2019-12-05 05:41:02.140 22032-22088/com.Test W/System.err:     at java.lang.Thread.run(Thread.java:919)
2019-12-05 05:41:06.317 22032-22070/com.Test V/FA: Inactivity, disconnecting from the service
2019-12-05 05:41:15.483 22032-22102/com.Test I/FirebaseCrash: Sending crashes

해결법 : 스레드 안에서 호출시 Dialog 로직을  핸들러(handler)로 감싸은 후 호출하면 해결된다.

Handler mHandler = new Handler(Looper.getMainLooper());
mHandler.postDelayed(new Runnable() {

   @Override
   public void run() {

       CheckFCM();
   }

},0);

스레드 사용시에는 주의해야한다.

Leave a Reply

error: Content is protected !!