1 private void connect() { 2 MyTask task = new MyTask(this); 3 task.execute(url.getText().toString()); 4 } 5 6 private class MyTask extends AsyncTask<String, Integer, String> { 7 private Context ctx; 8 private ProgressDialog pdialog; 9 public MyTask(Context ctx){ 10 super(); 11 this.ctx = ctx; 12 //创建ProgressDialog 13 pdialog = new ProgressDialog(ctx, 0); 14 pdialog.setButton("cancel", new DialogInterface.OnClickListener() { 15 public void onClick(DialogInterface dialog, int i) { 16 //dialog.cancel(); 17 } 18 }); 19 pdialog.setOnCancelListener(new DialogInterface.OnCancelListener() { 20 public void onCancel(DialogInterface dialog) { 21 finish(); 22 } 23 }); 24 pdialog.setCancelable(true); 25 pdialog.setMax(100); 26 pdialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 27 pdialog.show(); 28 } 29 30 //onPreExecute方法用于在执行后台任务前做一些UI操作 31 @Override 32 protected void onPreExecute() { 33 Log.i(TAG, "onPreExecute() called"); 34 //textView.setText("loading..."); 35 } 36 37 //doInBackground方法内部执行后台任务,不可在此方法内修改UI 38 @Override 39 protected String doInBackground(String... params) { 40 Log.i(TAG, "doInBackground(Params... params) called"); 41 try { 42 HttpClient client = new DefaultHttpClient(); 43 HttpGet get = new HttpGet(params[0]); 44 HttpResponse response = client.execute(get); 45 if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { 46 HttpEntity entity = response.getEntity(); 47 InputStream is = entity.getContent(); 48 long total = entity.getContentLength(); 49 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 50 byte[] buf = new byte[1024]; 51 int count = 0; 52 int length = -1; 53 while ((length = is.read(buf)) != -1) { 54 baos.write(buf, 0, length); 55 count += length; 56 //调用publishProgress公布进度,最后onProgressUpdate方法将被执行 57 publishProgress((int) ((count / (float) total) * 100)); 58 //为了演示进度,休眠500毫秒 59 Thread.sleep(500); 60 } 61 return new String(baos.toByteArray(), "gb2312"); 62 } 63 } catch (Exception e) { 64 Log.e(TAG, e.getMessage()); 65 } 66 return null; 67 } 68 69 //onProgressUpdate方法用于更新进度信息 70 @Override 71 protected void onProgressUpdate(Integer... values) { 72 Log.i(TAG, "onProgressUpdate(Progress... values) called"); 73 //pdialog.setProgress(values[0]); 74 //textView.setText("loading..." + values[0] + "%"); 75 } 76 77 //onPostExecute方法用于在执行完后台任务后更新UI,显示结果 78 @Override 79 protected void onPostExecute(String result) { 80 Log.i(TAG, "onPostExecute(Result result) called"); 81 //pdialog.dismiss(); 82 //textView.setText(result); 83 } 84 85 //onCancelled方法用于在取消执行中的任务时更改UI 86 @Override 87 protected void onCancelled() { 88 super.onCancelled(); 89 Log.i(TAG, "onCancelled() called"); 90 //textView.setText("cancelled"); 91 } 92 }