我正在编写一个程序,需要为服务器连接运行单独的线程,但我不知道如何正确使用AsyncTask
。我已阅读文档,但仍不确定如何正确使用它。如何使用AsyncTask?
这是应该给我连接到服务器的方法:
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;
}
的ListenFromServer类以上使用:
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("> ");
}
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) {
}
}
}
}
我知道我应该使用AsyncTask
,但我不知识。
有没有办法可以从AsyncTask返回一个变量?因为执行所有这些操作的方法需要返回一个布尔变量,所以许多其他方法和类都会询问'if(!start())return;' –
您需要使用回调函数。这很容易,并在[这篇文章]顶部的答案(http://stackoverflow.com/questions/12575068/how-to-get-the-result-of-onpostexecute-to-main-activity-because-asynctask-is- a)会告诉你如何去做。 – jburn2712