android:非同步任務asyncTask介紹及非同步任務下載圖片(帶進度條)

來源:互聯網
上載者:User

標籤:

為什麼要用非同步任務?

在android中只有在主線程才能對ui進行更新操作,而其它線程不能直接對ui進行操作

android本身是一個多線程的作業系統,我們不能把所有的操作都放在主線程中操作 ,比如一些耗時操作。如果放在主線程中 會造成阻塞 而當阻塞事件過長時 系統會拋出anr異常。所以我們要使用非同步任務。android為我們提供了一個封裝好的組件asynctask。

AsyncTask可以在子線程中更新ui,封裝簡化了非同步作業。適用於簡單的非同步處理。如果多個背景工作時就要使用Handler了 在這裡就不再說明。

AsyncTask通常用於被繼承。AsyncTask定義了三種泛型型別<Params,Progress,Result>

Params:啟動任務時輸入的參數類型

Progress:背景工作執行的百分比

Result:執行任務完成後返回結果的類型

繼承AsyncTask後要重寫的方法有:

doInBackgroud:必須重寫,非同步執行後台線程要完成的任務,耗時任務要寫在這裡,並且在這裡不能操作ui。可以調用 publishProgress方法來更新即時的任務進度

onPreExecute:執行耗時操作前調用,可以完成一些初始化操作

onPostExecute:在doInBackground 執行完成後,主線程調用此方法,可以在此方法中操作ui

onProgressUpdate:在doInBackgroud方法中調用publishProgress方法,更新任務的執行進度後 就會調用這個方法

下面通過一個執行個體來瞭解AsyncTask

首先附上運行結果


布局檔案:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <Button        android:id="@+id/btn_download"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center_horizontal"        android:text="點擊下載" />    <FrameLayout        android:layout_width="fill_parent"        android:layout_height="fill_parent" >        <ImageView            android:id="@+id/iv_image"            android:layout_width="fill_parent"            android:layout_height="fill_parent"            android:scaleType="fitCenter" />    </FrameLayout></LinearLayout>
MainActivity

package com.example.asynctask;import java.io.BufferedInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.MalformedURLException;import java.net.URLConnection;import android.os.AsyncTask;import android.os.Bundle;import android.app.Activity;import android.app.ProgressDialog;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.ImageView;public class MainActivity extends Activity implements OnClickListener{private ImageView image;private ProgressDialog progress;private Button btn_download;private static String URL="http://img4.imgtn.bdimg.com/it/u=1256159061,743487979&fm=21&gp=0.jpg";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);image=(ImageView) findViewById(R.id.iv_image);btn_download=(Button) findViewById(R.id.btn_download);progress=new ProgressDialog(this);progress.setIcon(R.drawable.ic_launcher);progress.setTitle("提示資訊");progress.setMessage("正在下載,請稍候...");progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);btn_download.setOnClickListener(this);}@Overridepublic void onClick(View v) {// TODO Auto-generated method stubnew MyAsyncTask().execute(URL);}/* * String*********對應我們的URL類型 * Integer********進度條的進度值 * BitMap*********非同步任務完成後返回的類型   * */class MyAsyncTask extends AsyncTask<String, Integer, Bitmap>{//執行非同步任務(doInBackground)之前執行,並且在ui線程中執行@Overrideprotected void onPreExecute() {// TODO Auto-generated method stubsuper.onPreExecute();if(image!=null){image.setVisibility(View.GONE);}//開始下載 對話方塊進度條顯示progress.show();progress.setProgress(0);}@Overrideprotected Bitmap doInBackground(String... params) {// TODO Auto-generated method stub//params是一個可變長的數組 在這裡我們只傳進來了一個url String url=params[0];Bitmap bitmap=null;URLConnection connection;InputStream is;//用於擷取資料的輸入資料流ByteArrayOutputStream bos;//可以捕獲記憶體緩衝區的資料,轉換成位元組數組。int len;float count=0,total;//count為圖片已經下載的大小 total為總大小try {//擷取網路連接對象connection=(URLConnection) new java.net.URL(url).openConnection();//擷取當前頁面的總長度total=(int)connection.getContentLength();//擷取輸入資料流is=connection.getInputStream();bos=new ByteArrayOutputStream();byte []data=new byte[1024];while((len=is.read(data))!=-1){count+=len;bos.write(data,0,len);//調用publishProgress公布進度,最後onProgressUpdate方法將被執行publishProgress((int)(count/total*100));//為了顯示出進度 人為休眠0.5秒Thread.sleep(500);}bitmap=BitmapFactory.decodeByteArray(bos.toByteArray(), 0, bos.toByteArray().length);is.close();bos.close();} catch (MalformedURLException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}return bitmap;}//在ui線程中執行 可以操作ui@Overrideprotected void onPostExecute(Bitmap bitmap) {// TODO Auto-generated method stubsuper.onPostExecute(bitmap);//下載完成 對話方塊進度條隱藏progress.cancel();image.setImageBitmap(bitmap);image.setVisibility(View.VISIBLE);}/* * 在doInBackground方法中已經調用publishProgress方法 更新任務的執行進度後 * 調用這個方法 實現進度條的更新 * */@Overrideprotected void onProgressUpdate(Integer... values) {// TODO Auto-generated method stubsuper.onProgressUpdate(values);progress.setProgress(values[0]);}}}

最後不要忘記在AndroidManifest檔案中配置網路存取權限

<uses-permission android:name="android.permission.INTERNET"/>


android:非同步任務asyncTask介紹及非同步任務下載圖片(帶進度條)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.