본문 바로가기

Programming/Error Note

[Android] java.lang.IllegalStateException: Main thread not allowed to quit.

[Error]java.lang.IllegalStateException: Main thread not allowed to quit.

123456789101112131415161718192021222324252627282909-17 19:09:28.921 6296-6296/com.tistory.gpark.nextstep E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.tistory.gpark.nextstep, PID: 6296
    java.lang.RuntimeException: Unable to destroy activity {com.tistory.gpark.nextstep/com.tistory.gpark.nextstep.JavaActivity}: java.lang.IllegalStateException: Main thread not allowed to quit.
        at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:5145)
        at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:5168)
        at android.app.ActivityThread.access$1700(ActivityThread.java:229)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1880)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:7406)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
     Caused by: java.lang.IllegalStateException: Main thread not allowed to quit.
        at android.os.MessageQueue.quit(MessageQueue.java:415)
        at android.os.Looper.quit(Looper.java:228)
        at com.tistory.gpark.nextstep.JavaActivity.onDestroy(JavaActivity.java:63)
        at android.app.Activity.performDestroy(Activity.java:7130)
        at android.app.Instrumentation.callActivityOnDestroy(Instrumentation.java:1171)
        at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:5123)
        at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:5168) 
        at android.app.ActivityThread.access$1700(ActivityThread.java:229) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1880) 
        at android.os.Handler.dispatchMessage(Handler.java:102) 
        at android.os.Looper.loop(Looper.java:148) 
        at android.app.ActivityThread.main(ActivityThread.java:7406) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 

Main Thread가 살아 있을때 Main Looper를 종료하려고 하면 발생하는 에러

Solution

Main Thread인지 체크하면 된다.

1boolean isUiThread = Looper.getMainLooper().getThread() == Thread.currentThread();

Marshmallow버전 이상(API Level 23)

1boolean isUiThread = Looper.getMainLooper().isCurrentThread();

Reference

Android - myLooper() vs getMainLooper() - Stack Overflow