[Android] Toast.makeText 에러 (AppName 앱을 중지하였습니다)

[Android] Toast.makeText 에러 (AppName 앱을 중지하였습니다)

안드로이드에서 토스트 메시지를 띄우는 코드는 다음과 같다.

public void doToastMsg(String str) {

    Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG).show();
}

그런데 이 코드에서 “AppName 앱을 중지하였습니다” 메시지가 표시되며 앱이 죽는 경우가 있다.

E/AndroidRuntime: FATAL EXCEPTION: Thread-4
    Process: secuwiz.net.serviceapitest, PID: 12497
    java.lang.RuntimeException: Can’t create handler inside thread that has not called Looper.prepare()
        at android.os.Handler.<init>(Handler.java:200)
        at android.os.Handler.<init>(Handler.java:114)
        at android.widget.Toast$TN.<init>(Toast.java:622)
        at android.widget.Toast.<init>(Toast.java:137)
        at android.widget.Toast.makeText(Toast.java:385)
        at secuwiz.net.serviceapitest.OtpActivity.doToastMsg(OtpActivity.java:284)
        at secuwiz.net.serviceapitest.OtpActivity$StartRunnable.run(OtpActivity.java:212)
        at java.lang.Thread.run(Thread.java:762)

위와 같이 Can’t create handler inside thread that has not called Looper.prepare() 에러가 출력될 경우, 아래처럼 코드를 고쳐준다.

public void doToastMsg(String str) {
    if (Looper.myLooper() == null) {
         Looper.prepare();
     }

     Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG).show();
     Looper.loop();
}

루퍼는 이벤트 루프와 메시지 큐의 레퍼런스를 가지고 있는 클래스이다. 

쓰레드가 메시지 큐에 접근할 수 있는 수단을 제공한다.

루퍼는 한 쓰레드에 단 1개만 존재할 수 있다. (한 번 더 생성하려고 시도할 경우 java.lang.RuntimeException: Only one Looper may be created per thread 오류가 발생)

Looper.prepare(); 코드로 루퍼를 생성하고,

Looper.loop(); 코드로 메시지 큐로부터 메시지를 디스패치 시킨다.

참고사이트) http://horajjan.blog.me/220963043229

https://m.blog.naver.com/kkk4687/220441125902