Android AsyncTask異步處理抓取網頁
Android AsyncTask異步處理抓取網頁
/*
- @author yanggang
@see http://blog.csdn.net/sunboy_2050 */ public class MainActivity extends Activity { private EditText metURL; private TextView mtvPage; private Button mbtnConn;
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); metURL = (EditText)findViewById(R.id.etURL); // 輸入網址 mbtnConn = (Button)findViewById(R.id.btnConn); // 連接網站 mtvPage = (TextView)findViewById(R.id.tvPage); // 顯示網頁 mbtnConn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { connURL(); } });
}
private void connURL(){
URLTask urlTask = new URLTask(this); // 實例化抽象AsyncTask urlTask.execute(metURL.getText().toString().trim()); // 調用AsyncTask,傳入url參數
}
/* 繼承AsyncTask的子類,下載url網頁內容 / class URLTask extends AsyncTask<String, Integer, String> {
ProgressDialog proDialog; public URLTask(Context context) { proDialog = new ProgressDialog(context, 0); proDialog.setButton("cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); proDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { finish(); } }); proDialog.setCancelable(true); proDialog.setMax(100); proDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); proDialog.show(); } @Override protected void onPreExecute(){ mtvPage.setText(R.string.hello_world); // 可以與UI控件交互 } @Override protected String doInBackground(String... params) { // 在后臺,下載url網頁內容 try { HttpGet get = new HttpGet(params[0]); // url HttpResponse response = new DefaultHttpClient().execute(get); if(response.getStatusLine().getStatusCode() == 200) { // 判斷網絡連接是否成功
// String result = EntityUtils.toString(response.getEntity(), "gb2312"); // 獲取網頁內容 // return result;
HttpEntity entity = response.getEntity(); long len = entity.getContentLength(); // 獲取url網頁內容總大小 InputStream is = entity.getContent(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int ch = -1; int count = 0; // 統計已下載的url網頁內容大小 while(is != null && (ch = is.read(buffer)) != -1 ) { bos.write(buffer, 0, ch); count += ch; if(len > 0) { float ratio = count/(float)len * 100; // 計算下載url網頁內容百分比 publishProgress((int)ratio); // android.os.AsyncTask.publishProgress(Integer... values) } Thread.sleep(100); } String result = new String(bos.toString("gb2312")); return result; } } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onProgressUpdate(Integer... values) { // 可以與UI控件交互 mtvPage.setText("" + values[0]); // 獲取 publishProgress((int)ratio)的values proDialog.setProgress(values[0]); } @Override protected void onPostExecute(String result) { // 可以與UI控件交互 mtvPage.setText(result); proDialog.dismiss(); }
} }</pre>
本文由用戶 cwf8 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!