多次调用Looper导致“将消息发送到死线程上的处理程序”

我正在使用带有自己的ThreadFactory的Executor [固定线程池],该线程工厂添加了Looper:

Handler HANDLER = new Handler();
Executor    THREADS = Executors.newFixedThreadPool(THREAD_POOL_SIZE, new ThreadFactory() {
    @Override public Thread newThread(Runnable runnable) {
        return new MyThread(new Runnable() {
            @Override public void run() {
                Looper.prepare();
                runnable.run();
            }
        });
    }
});

private static class MyHandler extends Handler {
    public boolean fail;
        public void handleMessage(Message msg) {
        switch(msg.what) {
            case 1:
                this.fail = msg.arg1 == 1;
                Looper.myLooper().quit();
                break;
            }
        }
    }
}

我正在运行发出网络请求的线程,但是如果网络失败,我希望向用户显示对话框消息.这个过程相当复杂,因为它需要在UI线程中进行AND显示请求.我可以通过简单地将Loop添加到网络线程并等待从UI线程发送消息来等待用户对对话框的响应.这使我可以将网络请求封装在while(tryAgain)线程中.除了第二次调用Looper.loop()方法(在显示第二个网络错误对话框之后)并且对话框(在UI线程中)将消息发送到网络线程的处理程序时,所有方法都运行良好:

THREADS.execute(new Runnable() {
    private MyHandler   myHandler   = new MyHandler();
    @Override public void run() {
        boolean tryAgain    = true;
        while(tryAgain) {
            try {
                switch(request) {
                    [Handle network requests]
                }
                tryAgain    = false;

            } catch(IOException e) {
                // The network is unavailable.  Ask the user if we should try again.
                e.printStackTrace();

            } finally {
                if(tryAgain) {
                    HANDLER.post(new Runnable() {   // The UI thread
                        @Override public void run() {
                            theAlertDialog.show();
                        }
                    });

                    // Wait for the results from the dialog which lives in the UI thread.
                    Looper.loop();

                    // At this point the dialog has informed us of our answer.
                    tryAgain = !myHandler.fail;
                }
            }
        }
    }
});

在AlertDialog实例中是一个OnClickListener:

DialogInterface.OnClickListener myOnclickListener = new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int id) {
        Message msg = myHandler.obtainMessage(1);
        msg.setTarget(this.handler);
        msg.sendToTarget();
    }
}

我已经使用handler.getLooper().getThread().isAlive()检查该线程是否仍处于活动状态,该方法始终返回true,但仍会给我“在死线程上向处理程序发送消息”.消息/处理程序如何确定线程已死?它不应该依赖.isAlive()方法吗?最后,我试图避免将线程管理版本复制到Android OS中:-)

解决方法:

如果您在android / os / MessageQueue.java中检查源代码,则会看到类似以下内容

  if (mQuiting) {
                RuntimeException e = new RuntimeException(
                    msg.target + " sending message to a Handler on a dead thread");
                Log.w("MessageQueue", e.getMessage(), e);
                return false;
            } else if (msg.target == null) {
                mQuiting = true;
            }
   }

因此,在第一次调用Looper.quit()之后,消息队列基本上无法使用,因为它使具有空目标的Message排队,这是消息队列停止排队并出现“死”的神奇标识符.

上一篇:Android Handler类 发送消息-post()和postDelay(), Looper讲解


下一篇:Java 将Word转为XML,XML转为Word的方法