Android Handler handleMessage

时间:2016-08-09 12:39:33

标签: android networking

有人可以告诉我为什么我在handleMessage

中获取主线程异常的网络

3 个答案:

答案 0 :(得分:0)

因为你在主线程中创建了处理程序的实例并且在它上面工作。在heandler中,您尝试在主线程中创建套接字连接(Internet连接)。

 /**
     * Default constructor associates this handler with the {@link 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.
     */
    public Handler() ;

答案 1 :(得分:0)

我猜您因Toast.makeText(getApplicationContext(), count, Toast.LENGTH_LONG).show();

而遇到异常

尝试使用新主题:

runOnUiThread(new Runnable() {
     @Override
     public void run() {
         showToast(MessageBuilder.SUCCESSFUL_COMMENT);
       }
  });

答案 2 :(得分:0)

您需要在后台运行处理程序。您可以使用Looper。 请参阅https://developer.android.com/reference/android/os/Looper.html

你可以试试这个:

    Thread thread = new Thread() {
        @Override
        public void run() {
            super.run();
            Looper.prepare();

            handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    try {
                        String tmp = msg.obj.toString();
                        InetAddress serverAddr = InetAddress.getByName(serverIP);
                        socket = new Socket(serverAddr, serverPort);
                        OutputStream outStream = socket.getOutputStream();
                        PrintWriter writer = new PrintWriter(outStream);
                        writer.write(tmp);
                        writer.flush();
                        InputStream inStream = socket.getInputStream();
                        byte[] xxx = new byte[20];
                        int count = inStream.read(xxx);
//          Toast.makeText(getApplicationContext(), count, Toast.LENGTH_LONG).show();

                        outStream.flush();
                        outStream.close();

                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        Looper.myLooper().quit();
                    }
                }

            };
            handler.removeCallbacks(this);
            Looper.loop();
        }
    };

    thread.start();

此外,您在处理程序中显示Toast,这将导致RuntimeError。请从处理程序中删除Toast。