public class AsyncTaskExample extends AsyncTask<String, Void, Boolean>{
private ProgressDialog progressDialog;
private Activity activity;
public AsyncTaskExample(Activity activity, ProgressDialog progress) {
activity = activity;
progressDialog = progress;
}
@Override
protected void onPreExecute(){
progressDialog.show();
}
@Override
protected Boolean doInBackground(String... params) {
//params is array of strings containing values which are passing while calling this AsyncTaskExample
int responseCode;
String responseString;
List<BasicNameValuePair> nameValuePairs = null;
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = 20000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 20000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost("YOUR_URL");
HttpResponse response;
nameValuePairs = new ArrayList<BasicNameValuePair>();
nameValuePairs.add(new BasicNameValuePair("user", varTwo ));
nameValuePairs.add(new BasicNameValuePair("password", varThree ));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httpPost);
responseCode = response.getStatusLine().getStatusCode();
responseString = EntityUtils.toString(response.getEntity());
return isSuccess;
}
@Override
protected void onPostExecute(Boolean isSuccess){
try {
progressDialog.dismiss();
} catch (Exception e) {
Log.e(TAG, "Error while closing dialog");
}
}
在代码中的某个位置调用 AsyncTaskExample,例如
AsyncTaskExample loginTask = new AsyncTaskExample (this, progressDialog);
task.execute(userName, password);
// here userName, password are the params which should paass to your webservice, it will get in doInBackGroung by params variable as params[0], params[1]
you should also have internet permission in manifest file