使用AsyncTask在按钮单击时执行网络操作为:
public class onbuttonclickHttpPost extends AsyncTask<String, Void, Void> { @Override protected String doInBackground(String... params) { byte[] result = null; String str = ""; // Create a new HttpClient and Post Header HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php"); try { // Add your data List<NamevaluePair> namevaluePairs = new ArrayList<NamevaluePair>(2); namevaluePairs.add(new BasicNamevaluePair("id", "12345")); namevaluePairs.add(new BasicNamevaluePair("stringdata", "AndDev is Cool!")); httppost.setEntity(new UrlEnpredFormEntity(namevaluePairs)); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost); StatusLine statusLine = response.getStatusLine(); if(statusLine.getStatusCode() == HttpURLConnection.HTTP_OK){ result = EntityUtils.toByteArray(response.getEntity()); str = new String(result, "UTF-8"); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block } catch (IOException e) { // TODO Auto-generated catch block } return str; } @Override protected void onPostExecute(String result) { // something with data retrieved from server in doInBackground }}然后在Button上单击Start AsyncTask onbuttonclickHttpPost作为:
buttonclick.setonClickListener(new View.onClickListener() { public void onClick(View v) { new onbuttonclickHttpPost.execute(null); } });


