Example: Android bi-directional network socket using AsyncTask

后端 未结 3 2078
醉酒成梦
醉酒成梦 2020-11-27 11:48

Most of the network socket examples I found for Android were one directional only. I needed a solution for a bi-directional data stream. I eventually learned of the AsyncTas

3条回答
  •  囚心锁ツ
    2020-11-27 12:18

    The SendDataToNetwork task runs in the main ui thread, meaning it will crash a Honeycomb or higher app due to NetworkOnMainThreadException Fatal exception. Here's what my SendDataToNetwork looks like to avoid this issue:

    public boolean sendDataToNetwork(final byte[] cmd) { 
        if (_nsocket.isConnected()) {
            Log.i(TAG, "SendDataToNetwork: Writing received message to socket");
            new Thread(new Runnable() {
                public void run() {
                    try {
                        _nos.write(cmd);
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.i(TAG, "SendDataToNetwork: Message send failed. Caught an exception");
                    }
                }
            }).start();
    
            return true;
        }
    
        Log.i(TAG, "SendDataToNetwork: Cannot send message. Socket is closed");
        return false;
    }
    

提交回复
热议问题