老实说,AsyncTask是最麻烦的方法,我永远不会习惯它的作用,
这是我的AsyncTask代码:
public class myAsync extends AsyncTask<String, Boolean, Boolean>{
boolean thisisresult=false;
@Override
protected Boolean doInBackground(String...urls){
try {
socket = new Socket(server, port);
}
catch(Exception ec) {
Log.i(LOGTAG,"Error connectiong to server:" + ec);
return false;
}
String msg = "Connection accepted " + socket.getInetAddress() + ":" +
socket.getPort();
Log.i(LOGTAG, msg);
try
{
sInput = new ObjectInputStream(socket.getInputStream());
sOutput = new ObjectOutputStream(socket.getOutputStream());
}
catch (IOException eIO) {
Log.i(LOGTAG,"Exception creating new Input/output Streams: " +
eIO);
return false;
}
try
{
EditText u=(EditText)findViewById(R.id.inputuser);
theuser = u.getText().toString();
EditText p =(EditText)findViewById(R.id.inputpassword);
thepass = p.getText().toString();
EditText n =(EditText)findViewById(R.id.realname);
thename = n.getText().toString();
EditText m =(EditText)findViewById(R.id.inputmail);
themail = m.getText().toString();
EditText ph = (EditText)findViewById(R.id.inputphone);
thephone = ph.getText().toString();
int RID=RandomNumbers.Rgenerate();
String newRID = Integer.toString(RID);
sOutput.writeObject(theuser);
sOutput.writeObject(thepass);
sOutput.writeObject(thename);
sOutput.writeObject(themail);
sOutput.writeObject(thephone);
sOutput.writeObject(newRID);
sOutput.flush();
Log.i(LOGTAG,"this"+theuser + thepass + thephone +
themail + thename+ newRID);
String REresponse = (String) sInput.readObject();
while(recieved==false)
{
if (REresponse.equals("('T','"+newRID+"')")){
Log.i(LOGTAG,"you made it");
// showthis=("اکانت با موفقیت ساخته شد");
recieved = true;
thisisresult=true;
}else if (REresponse.equals("('F','"+newRID+"')")){
Log.i(LOGTAG,"you failed");
// showthis=("username تکراری است");
recieved=true;
thisisresult=true;
}else{
// showthis=("جوابی از سرور دریافت نشد");
Log.i(LOGTAG,REresponse);
Log.i(LOGTAG,"some thing is wrong");
}
}
}
catch (IOException eIO) {
// display("Exception doing login : " + eIO);
Log.i(LOGTAG,"Exception doing login : " + eIO);
disconnect();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// success we inform the caller that it worked
return true;
}
}
protected void onPostExecute(Boolean result){
TextView tv = (TextView) findViewById(R.id.alerttext);
if(result==true){
tv.setText("done");
}
else{
tv.setText("Not done");
}
底部我的异步应该返回布尔值true,因为我已将其设置为TRUE,但它没有,有没有人掌握这种方法来帮助我?
答案 0 :(得分:1)
来自Android文档:
异步任务使用的三种类型如下:
- Params,执行时发送给任务的参数类型。
这是第一个传递的类型。这允许您使用execute
方法传递内容
- 进度,后台计算期间发布的进度单位的类型。
这是作为参数传递给onProgressUpdate
方法
- 结果,后台计算结果的类型。
这是从doInBackground
方法到onPostExecute
onPostExecute
将始终具有返回类型void。
如果您的其他方法在等待AsyncTask
的返回值时阻止了UI线程,则会取消AsyncTask
的使用