title: Android TCP connection best practice
body: <p>I am working on an Android application that requires a TCP connection to a TCP server(Written in Node.js)</p>
  
  <p>My Android TCP client is working an can send messages back and forth.</p>
  
  <p>My spesific questions is: </p>
  
  <ol>
  <li>What is the best way to handle a TCP connection to a server in Android ?</li>
  <li>How to maintain the connection(close the connection properly on onDestroy() etc) ?</li>
  <li>Is there any bether way then using an AsyncTask(Except a normal Thread class, which is not allowed in Android 4.0)</li>
  </ol>
  
  <p>I have my socket connection in an AsyncTask like this:</p>
  
  <pre><code>@Override
  protected Void doInBackground(Void... params) {
          try {
              Log.d("TCP_MESSAGE", "Connecting...");
  
                  socket = new Socket(MY_LOCAL_IP, 8080);
                  dataOutput = new DataOutputStream(socket.getOutputStream());
  
                  inputstream = new InputStreamReader(socket.getInputStream());
                  input = new BufferedReader(inputstream);
  
  
              while (!canceled) {
                  String message = input.readLine();
                  handleMessage(message);
              }
  
          } catch (Exception e) {
              e.printStackTrace();
          }
      }
      return null;
  }
  </code></pre>
  
  <p>The reason i have the connection in an AsyncTask is because i am using android 4.0 and are not allowed to have network code in a regular Thread.</p>