老罗AsyncTask(20)带进度条下载图片例子

来源:互联网 发布:格博cad软件下载 编辑:程序博客网 时间:2024/04/27 16:57

布局文件

<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下载图片例子

0 0