我正在使用这个asynctask类来更新Sql Server上的两个不同的表到目前为止这段代码工作得很好我对这个类的更好和更充分的代码结构感兴趣特别在doinbackground()
是否可以在单个线程中调用多个webservices方法?任何人都可以建议我吗?
private class Update extends AsyncTask<Void, Void, Integer> {
private final int FAILED_INVALID_RESPONSE = 0;
private final int SUCCESS_GET_DATA = 1;
ProgressDialog progress;
private String _phoneno;
private String _ticket;
UpdateTicket(String phoneno,String ticket){
_phoneno=phoneno;
_ticket=ticket;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
progress = ProgressDialog.show(XYZ.this, "",
"In Progress...", false);
}
@Override
protected Integer doInBackground(Void... params) {
method1(_phoneno);
return method2(_phoneno,_ticket);
}
@Override
protected void onPostExecute(Integer result) {
progress.dismiss();
switch (result) {
case FAILED_INVALID_RESPONSE:
Toast.makeText(XYZ.this,"Please Check your Internet Connection.",Toast.LENGTH_SHORT).show();
break;
case SUCCESS_GET_DATA:
Toast.makeText(XYZ.this, "Success!", Toast.LENGTH_SHORT).show();
break;
}
}
int method1(String phoneno,String tickets)
{
final String methodname = "firstmethod";
final String NAMESPACE ="http://tempuri.org/";
final String URL="www.sampleurl.com";
final String SOAP_ACTION="http://tempuri.org/firstmethod";
int success=0;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
SoapObject request = new SoapObject(NAMESPACE, methodname);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
request.addProperty("phoneno", phoneno);
request.addProperty("tickets", tickets);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try{
androidHttpTransport.call(SOAP_ACTION,envelope);
SoapObject response = (SoapObject) envelope.bodyIn;
if(response!=null){
success=1;
}
}
catch (Exception e)
{
e.printStackTrace();
}
return success;
}
int method2(String Phone) {
final String methodname = "secondmethod";
final String NAMESPACE ="http://tempuri.org/";
final String URL="www.sampleurl.com";
final String SOAP_ACTION="http://tempuri.org/secondmethod";
int success=0;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
SoapObject request = new SoapObject(NAMESPACE, methodname);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
request.addProperty("phoneno", phoneno);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try{
androidHttpTransport.call(SOAP_ACTION,envelope);
SoapObject response = (SoapObject) envelope.bodyIn;
if(response!=null){
success=1;
}
}
catch (Exception e)
{
e.printStackTrace();
}
return success;
}
}
答案 0 :(得分:1)
AsyncTask只能用于需要几秒钟的任务/操作。
AsyncTasks在单个后台线程(来自API 11)上串行执行。因此,长时间跑步的工人可以阻止他人。
检查其他gotchas。
看看HeandlerThread。