title: Android: Cancel Async-Task and restart it
body: <p>I coded an app to connect to my server via tcp/ip. (took the original code from a tutorial, but changed it)</p>
  
  <p>There I have an Async-Task where I connect to my Server and wait for messages.
  So this Task will never stop.</p>
  
  <p>I start it with:</p>
  
  <pre><code>conTask = new ConnectTask().execute("");
  </code></pre>
  
  <p>The Task looks like this:</p>
  
  <pre><code>public class ConnectTask extends AsyncTask&lt;String, String, TcpClient&gt; {
  
      @Override
      protected TcpClient doInBackground(String... message) {
  
          if (isCancelled()) {
              Log.d("async", "ASYNC CANCELED!!!");
              return null;
          }
  
          //we create a TCPClient object and
          mTcpClient = new TcpClient(new TcpClient.OnMessageReceived() {
  
              @Override
              public void reconnect()
              {
                  Log.d("recon", "here i can try to reconnect");
  
                  reConnect();
              }
  
              @Override
              //here the messageReceived method is implemented
              public void messageReceived(String message) {
                  //this method calls the onProgressUpdate
                  if (message.equals("connected"))
                  {
                      ...
                  }
              }
          });
  
          mTcpClient.run();
  
          return null;
      }
  }
  </code></pre>
  
  <p>The problem is, I try to reconnect, when the connection fails or breaks.
  If this happens, my TcpClient-Instance calls the reconnect()-Method where I call the reConnect()-Method from my Mainclass, where I try to kill the Async-Task and restart it:</p>
  
  <pre><code>    conTask.cancel(true);
      conTask = null;
  
      // disconnect
      mTcpClient.setMRun(false);
      mTcpClient.stopClient();
      mTcpClient = null;
  
     conTask = new ConnectTask().execute("");
  </code></pre>
  
  <p>It works fine, but suddenly while reconnecting, the App stops running and I don't know why. It repeatingly calls the reconnect-Method, for example if WLAN is off. And it works if I turn it on fast. But if I wait too long, the app is already crashed.</p>
  
  <p>So my final question is: How do I stop an Async-Task from within and restart it? Obviously I do something wrong.</p>
  
  <p>I would appreciate some help!</p>