Example: Android bi-directional network socket using AsyncTask

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;
}

Leave a Comment