title: How to use AsyncTask?
body: <p>I am writing a program and need to run separate thread for server connection, but I don't know how to properly use the <code>AsyncTask</code>. I have read the documentation and am still not certain as to how I would properly use it.</p>
  
  <p>The method that's supposed to connect me to the server:</p>
  
  <pre><code>public boolean start()
  {
      // try to connect to the server
      try {
          socket = new Socket(server, port);
      }
      // if it failed not much I can so
      catch(Exception ec) {
          display("Error connectiong to server:" + ec);
          return false;
      }
  
      /* Creating both Data Stream */
      try
      {
          sInput  = new ObjectInputStream(socket.getInputStream());
          sOutput = new ObjectOutputStream(socket.getOutputStream());
      }
      catch (IOException eIO) {
          display("Exception creating new Input/output Streams: " + eIO);
          return false;
      }
  
      // creates the Thread to listen from the server
      new ListenFromServer().start();
      // Send our username to the server this is the only message that we
      // will send as a String. All other messages will be ChatMessage objects
      try
      {
          sOutput.writeObject(username);
      }
      catch (IOException eIO) {
          display("Exception doing login : " + eIO);
          disconnect();
          return false;
      }
      // success we inform the caller that it worked
      return true;
  }
  </code></pre>
  
  <p>The ListenFromServer class used above:</p>
  
  <pre><code>class ListenFromServer extends Thread {
  
      public void run() {
          while(true) {
              try {
                  String msg = (String) sInput.readObject();
                  // if console mode print the message and add back the prompt
                  if(clientActivity == null) {
                      System.out.println(msg);
                      System.out.print("&gt; ");
                  }
                  else {
                      clientActivity.append(msg);
                  }
              }
              catch(IOException e) {
                  if(clientActivity != null)
                      clientActivity.connectionFailed();
                  display("Server has close the connection: " + e);
                  break;
              }
              // can't happen with a String object but need the catch anyhow
              catch(ClassNotFoundException e2) {
              }
          }
      }
  }
  </code></pre>
  
  <p>I know that I am supposed to use <code>AsyncTask</code>, but I don't know how.</p>