android套接字应用程序中的AsyncTask

时间:2014-05-16 00:59:55

标签: android android-asynctask

我正在制作一个Android套接字应用程序与服务器进行通信以创建帐户,我注意到我必须在AsyncTask子类中执行此操作,即使我将其分离到没有UI的另一个类,但我非常困惑怎么能我在这上面使用AsyncTask,这里有没有一位专家可以帮助我?

这是代码:

public class AccountCreator extends Activity {

public AccountCreator(){
 super();
 }
// for I/O
ObjectInputStream sInput;       // to read from the socket
ObjectOutputStream sOutput;     // to write on the socket
 Socket socket;
public static String LOGTAG="Lifemate";
public String server = "localhost";  
public String username = "user"; 
public String password = "rezapassword" ;
public int port = 1400;




@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

Log.i(LOGTAG,"oncreate called");
this.start();
}


AccountCreator(String server, int port, String username,String password) {
        this.server = "localhost";
        this.port = 1400;
        this.username = username;
        Log.i(LOGTAG,"first accountcreator called");
}

  public boolean start() {

      // try to connect to the server
//this method returns a value of true or false when called 

      try {
        socket = new Socket(server, port);
    }
        // if it failed not much I can so
    catch(Exception ec) {
//            display("Error connectiong to server:" + ec);
        Log.i(LOGTAG,"Error connectiong to server:" + ec);
        return false;
   }
    String msg = "Connection accepted " + socket.getInetAddress() + ":" + 
socket.getPort();
//        display(msg);
    Log.i(LOGTAG, msg);
    /* 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);
        Log.i(LOGTAG,"Exception creating new Input/output Streams: " + 
 eIO);
        return false;
    }

    // creates the Thread to listen from the server 

    // 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);
        sOutput.writeObject(password);

    }
    catch (IOException eIO) {
//          display("Exception doing login : " + eIO);
        Log.i(LOGTAG,"Exception doing login : " + eIO);
        disconnect();
        return false;
    }
    // success we inform the caller that it worked
    return true;
}

 //            private void display(String msg) {
 //             TextView screenprint = (TextView)findViewById(R.id.systemmessages);

 //             screenprint.setText(msg);


//    }

        private void disconnect() {
            Log.i(LOGTAG,"reached disconnect");
            try { 
                if(sInput != null) sInput.close();
            }
            catch(Exception e) {} // not much else I can do
            try {
                if(sOutput != null) sOutput.close();
            }
            catch(Exception e) {} // not much else I can do
            try{
                if(socket != null) socket.close();
            }
            catch(Exception e) {} // not much else I can do
        }

  public void Begin() {             
      Log.i(LOGTAG,"it begun"); 
      int portNumber = 1400;
      String serverAddress = server;
      String userName = username;
      String newpassword = password;
 AccountCreator accountcreator = new AccountCreator(serverAddress, portNumber, 
 userName,password);

            if(!accountcreator.start())
            return;


  }
 }    

我试图将整个代码放入Async中,我不知道我是否正确,我是否还需要这样做或只是其中某些部分呢?

2 个答案:

答案 0 :(得分:2)

简而言之, AsyncTask 包含一些可能有用的方法:

onPreExecute

  • 此方法是调用asyncTask.execute();时执行的第一个代码块(在 mainUIThread 上运行)。

doInBackground

  • 在这里,您将所有可能暂停主UI的代码(导致您的应用程序挂起),如互联网请求,或任何可能需要大量内存和处理的处理。 (在后台线程上运行),包含一个取自asyncTask.execute(ParameterType parameter);
  • 的参数

onPostExecute

  • doInBackground()之后运行。它的参数是doInBackground函数的返回值,主要是你需要在连接完成后在UI中进行更改(在 mainUIThread 上运行)

答案 1 :(得分:2)

您必须在已创建的类中声明另一个类。

class SomeName extends Async<Void, String, Void>{ 

    protected void OnPreExecute(){
        // starts the task runs on main UI thread
        // Can be used to start a progress dialog to show the user progress
    }

    @Override
    protected Void doInBackground(Void... params){
        // does what you want it to do in the background
        // Connected to the server to check a log-in
        return result;
    }

    protected void OnPostExecute(Void result){
        // finishes the task and can provide information back on the main UI thread
        // this would be were you would dismiss the progress dialog
    }
}