老羅AsyncTask(20)帶進度條下載圖片例子

佈局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />

    <Button android:id="@+id/download"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="下載圖片"/>
</LinearLayout>
public class MainActivity extends Activity {

    private Button mButton;
    private ImageView mImageView;
    private String path = "http://f.hiphotos.baidu.com/baike/c0%3Dbaike80%2C5%2C5%2C80%2C26/sign=c8306d71f5deb48fef64a98c9176514c/0b55b319ebc4b74576634006c9fc1e178a82152e.jpg";
    private ProgressDialog mProgressDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mButton = (Button)this.findViewById(R.id.download);
        mImageView = (ImageView)this.findViewById(R.id.imageView1);
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setTitle("等待下載");
        mProgressDialog.setMessage("正在下載");
        //設置等待進度條風格
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        //避免點擊其他位置將下載條隱藏,也就是進度條直到下載完才能消失
        mProgressDialog.setCancelable(false);
        mButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                MyTask task = new MyTask();
                task.execute(path);
            }
        });
    }
    private class MyTask extends AsyncTask<String, Integer, Bitmap>{
        @Override
        protected void onPreExecute() {
            mProgressDialog.show();
            super.onPreExecute();
        }

        @Override
        protected Bitmap doInBackground(String... arg0) {
            //從程序到電腦上,ByteArrayOutputStream 用於將圖片讀取放在內存緩衝區裏
            ByteArrayOutputStream outputstream = new ByteArrayOutputStream();
            InputStream inputStream = null;
            Bitmap bitmap = null;
            try {
                //完成對圖片的下載功能
                HttpClient client = new DefaultHttpClient();
                HttpGet get = new HttpGet(arg0[0]);
                HttpResponse response = client.execute(get);
                if(response.getStatusLine().getStatusCode() == 200){
                    inputStream = response.getEntity().getContent();
                    //先要獲得文件的總長度
                    long fileLenth = response.getEntity().getContentLength();
                    int lenth = 0;
                    int total_lenth = 0;
                    byte[] data = new byte[1024];
                    //read(byte[] b) 從輸入流中讀取一定數量的字節並將其存儲在緩衝區數組 b 中。以整數形式返回實際讀取的字節數
                    while((lenth = inputStream.read(data)) != -1){
                        total_lenth += lenth;
                        //聲明一個刻度
                        int values = 0;
                        values = (int) ((total_lenth / (float) fileLenth) * 100);
                        //將刻度發佈出去
                        publishProgress(values);
                        //每讀1024個字節放到字節流中
                        outputstream.write(data,0,lenth);
                    }
                    byte[] res = outputstream.toByteArray();
                    //將字節流轉換成字節數組
                    bitmap = BitmapFactory.decodeByteArray(res, 0, res.length);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally{
                if(inputStream != null){
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return bitmap;
        }


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

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

記得在AndroidManifest.xml文件中添加

<uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="19" />
    <uses-permission android:name="android.permission.INTERNET"/>

結果:
這裏寫圖片描述
相關參考:老羅Android(19)AsyncTask下載圖片例子

發佈了111 篇原創文章 · 獲贊 10 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章