본문 바로가기

Programming/Error Note

[Android] java.lang.IllegalStateException: This message is already in use.

[Error] java.lang.IllegalStateException: This message is already in use.

1234567891011121314151609-17 19:01:27.286 5673-5673/com.tistory.gpark.nextstep E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.tistory.gpark.nextstep, PID: 5673
    java.lang.IllegalStateException: { when=0 what=1 obj=메시지입니다.^^ target=android.os.Handler } This message is already in use.
        at android.os.MessageQueue.enqueueMessage(MessageQueue.java:538)
        at android.os.Handler.enqueueMessage(Handler.java:631)
        at android.os.Handler.sendMessageAtTime(Handler.java:600)
        at android.os.Handler.sendMessageDelayed(Handler.java:570)
        at android.os.Handler.sendMessage(Handler.java:507)
        at com.tistory.gpark.nextstep.JavaActivity$3.run(JavaActivity.java:46)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        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)

문제의 코드

123456Message msg = Message.obtain();
msg.what = 1;
msg.obj = "메시지입니다.^^";
for(Handler handler: mHandlers) {
    handler.sendMessage(msg);
}

하나의 Message로 여러 Handler에 send할 경우 발생하는 에러

Solution

123456for(Handler handler: mHandlers) {
    Message msg = Message.obtain();
    msg.what = 1;
    msg.obj = "메시지입니다.^^";
    handler.sendMessage(msg);
}