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

时光怂恿深爱的人放手 提交于 2019-12-02 06:29:21

How can you manage the request sent to a handler if your thread is not listening on a looper?

Doc says: public Handler ()

Added in API level 1 Default constructor associates this handler with the Looper for the current thread. If this thread does not have a looper, this handler won't be able to receive messages so an exception is thrown.

If you want a secondary thread to be able to manage a Handler you must call Looper.prepare()

Example:

public class MyThread extends Thread {
    private Handler mHandler;

    public void run() {
        Looper.prepare();
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    // manage the message
                }
            }
        };
        Looper.loop();
    }

    public void stopLooper() {
        if (Looper.myLooper()!=null)
            Looper.myLooper().quitSafely();
    }
}

You handler may be created in another thread, not main which does not have looper. To avoid this you should create handler in thread with looper (ex: in main thread, in onCreate), or provide looper to a handler:

private Handler handler = new Handler(Looper.getMainLooper()) {
    ...

Your approach to perform action in the background is really odd (i.e. Activity implements Runnable). I guess, the problem lays in the way you call downloadData() method, perhaps, from other background threads. (By the way, how do you call it, i.e. where do you store the reference to the MainActivity?)

Your task is easily solved by Loaders, which perfectly match Activity's lifecycle and requires much less code.

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