AsyncTask(非同步任務)講解-android的學習之旅(四十六),asynctask-android
AsyncTask簡介Android的UI線程主要處理使用者的按鍵,觸屏和View的繪製等,不能在裡面處理耗時的操作,否則會出現ANR,因此耗時的操作要單獨開一個線程處理,但是新線程不能直接處理UI線程的View。
AsyncTask的使用方法
程式碼範例
本執行個體只有一個按鈕和文字框,點擊按鈕從網路下載資料,然後又在文字框顯示。
package peng.liu.test;import android.app.Activity;import android.app.ProgressDialog;import android.content.Context;import android.os.AsyncTask;import android.os.Bundle;import android.view.View;import android.widget.TextView;import java.io.BufferedReader;import java.io.InputStreamReader;import java.net.MalformedURLException;import java.net.URL;import java.net.URLConnection;public class MainActivity extends Activity{ private TextView tvAsync; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvAsync = (TextView) findViewById(R.id.tvAsync); } public void download(View source) throws MalformedURLException { DownTask downTask = new DownTask(this); downTask.execute(new URL("http://www.carzyit.org/ethos.php")); } class DownTask extends AsyncTask<URL,Integer,String>{ ProgressDialog dialog; int hasdata; Context context; public DownTask(Context ctx){ this.context = ctx; } @Override protected String doInBackground(URL... urls) { StringBuilder sb = new StringBuilder(); try { URLConnection conn = urls[0].openConnection(); BufferedReader bf = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8")); String line = null; while ((line = bf.readLine()) != null){ sb.append(line); hasdata++; publishProgress(hasdata); } return sb.toString(); } catch (Exception e){ e.printStackTrace(); } return null; } @Override protected void onPostExecute(String s) { tvAsync.setText(s); dialog.dismiss(); } @Override protected void onPreExecute() { dialog = new ProgressDialog(context); dialog.setTitle("hello"); dialog.setCancelable(false); dialog.setMessage("world"); dialog.setMax(202); dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); dialog.setIndeterminate(false); dialog.show(); } @Override protected void onProgressUpdate(Integer... values) { tvAsync.setText(hasdata+""); dialog.setProgress(values[0]); } }}