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

China☆狼群 提交于 2019-12-01 10:39:17

问题


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.



来源:https://stackoverflow.com/questions/6732529/cant-create-handler-looper-prepare-in-inherited-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!