Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 非同步任務 AsyncTask 學習筆記

編輯:關於 Android 程式設計

Android 的非同步任務能很方便地完成耗時操作並更新 UI,不像多執行緒還得透過訊息佇列,由子執行緒發訊息給主執行緒才能更新介面。總的來說,AsyncTask 把多執行緒的互動進一步封裝,用起来更加方便。

以下是一個非同步下載圖片並更新介面的 demo:

 public class MainActivity extends Activity {
   private Button btn = null;
   private ImageView image = null;
   private String image_path = "https://f2.sjbly.cn/m13/0729/1459/6947edn_690x459_b.jpg";
   private ProgressDialog dialog;

   @Override protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     btn = (Button) this.findViewById(R.id.button1);
     dialog = new ProgressDialog(this);
     dialog.setTitle("提示信息");
     dialog.setMessage("下載中,請稍等......");
     dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); // 進度條樣式
     dialog.setCancelable(false); // 螢幕不失去焦點
     image = (ImageView) this.findViewById(R.id.imageView1);
     btn.setOnClickListener(new OnClickListener() {
       @Override public void onClick(View v) {
         new MyTask().execute(image_path);
       }
     });
   }

   public class MyTask extends AsyncTask<String, Integer, Bitmap> {
     @Override protected void onPreExecute() {
       dialog.show();
       super.onPreExecute();
     }

     @Override protected Bitmap doInBackground(String... params) {
       ByteArrayOutputStream out = new ByteArrayOutputStream(); // 記憶體流,不需關閉
       InputStream in = null;
       Bitmap bitmap = null;
       HttpClient httpClient = new DefaultHttpClient(); // 透過 HttpClient 取得網路資源
       HttpGet httpGet = new HttpGet(params[0]); // 注意請求網址要寫入
       try {
         HttpResponse httpResponse = httpClient.execute(httpGet);
         if (httpResponse.getStatusLine().getStatusCode() == 200) {
           in = httpResponse.getEntity().getContent(); // 取得輸入流
           long file_length = httpResponse.getEntity().getContentLength(); // 檔案總長度
           int total_len = 0;
           int len = 0;
           byte[] buffer = new byte[1024];
           try {
             while ((len = in.read(buffer)) != -1) {
               total_len += len;
               int value = (int) (total_len / ((float) file_length) * 100); // 計算進度
               publishProgress(value); // 發布進度
               out.write(buffer, 0, len); // 寫入輸出流
             }
             bitmap = BitmapFactory.decodeByteArray(out.toByteArray(), 0, out.toByteArray().length);
           } catch (Exception e) {
           } finally {
             if (in != null) { in.close(); }
           }
         }
       } catch (ClientProtocolException e) {
         e.printStackTrace();
       } catch (IOException e) {
         e.printStackTrace();
       }
       return bitmap;
     }

     @Override protected void onPostExecute(Bitmap result) {
       super.onPostExecute(result);
       image.setImageBitmap(result);
       dialog.dismiss();
     }

     @Override protected void onProgressUpdate(Integer... values) {
       super.onProgressUpdate(values);
       dialog.setProgress(values[0]);
     }
   }
 }

其中 publishProgress(value); 可以發送一個或多個物件給 onProgressUpdate() 方法,通常用來更新進度條。

DEMO 下載:https://download.csdn.net/detail/u014600432/8175337

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved