-->

`Can't create handler…Looper.prepare()` in inh

2019-02-20 15:41发布

问题:

I have a Game Activity (Activity A) that works well with all the code. Then I create a new Activity (Activity B) for my new game mode, that extends Activity A. However, when encounter the Toast line, Activity B suddenly thrown an exception (Activity A works well showing the Toast):

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

Activity B only overrides a load-level method, no any differrence!

回答1:

Try this:

Handler innerHandler;

(new Thread(new Runnable() {

            @Override
            public void run() {
                Looper.prepare();

                innerHandler = new Handler() {
                    @Override
                    public void handleMessage(Message message) {
                        Toast.make(...);
                    }

                    @Override
                    public void dispatchMessage(Message message) {
                        handleMessage(message);
                    }
                };

                Message message = innerHandler.obtainMessage();
                innerHandler.dispatchMessage(message);
                Looper.loop();
            }
        })).start();

There may be an easier way to handle the problem. Please refer to Android – Multithreading in a UI environment documentation.