Android AsyncTask异步实现大文件下载

来源:互联网 发布:淘宝退货发空包犯法吗 编辑:程序博客网 时间:2024/05/21 06:34

Android AsyncTask异步实现大文件下载

![异步下载显示图片](http://img.blog.csdn.net/20151114001557431)public class Third extends Activity {    private Button btn;    private ImageView iv;    private TextView textview;    private Handler handlers;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        this.setContentView(R.layout.download);        btn = (Button) findViewById(R.id.btn);        iv = (ImageView) findViewById(R.id.iv);        textview = (TextView) findViewById(R.id.textview);        btn.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                DownLoadImageTask imt = new DownLoadImageTask();                imt.execute("http://img2.niutuku.com/desk/1208/0850/bizhi-0850-17120.jpg");//传一个网址            }        });        handlers = new Handler(){            @Override            public void handleMessage(Message msg) {                super.handleMessage(msg);                if(msg.what==0x001){                    Log.e("---------------------", "" + msg.obj);                    textview.setText(msg.obj.toString());                }else if(msg.what==0x002){                    Bitmap bitmap = (Bitmap) msg.obj;                    iv.setImageBitmap(bitmap);                }            }        };    }    /**     * 完成图片下载的异步任务     * @author Administrator     *     */    class DownLoadImageTask            extends AsyncTask<String, Integer, byte[]> {//参数含义:传进去的值;后台百分比;返回的结果        private ProgressDialog progressDialog;//进度条        private byte[] current = new byte[2 * 1024];//每次读到的字节数组        private byte[] total;//下载图片后汇总的字节数组        private boolean flag; //是否被取消        //任务执行之前回调        @Override        protected void onPreExecute() {            progressDialog = new ProgressDialog(Third.this);            progressDialog.setMessage("正在操作中,请稍候……");            progressDialog.setMax(100);//进度条最大值            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);//水平样式            progressDialog.setIndeterminate(false);//进度条的动画效果(有动画则无进度值)            flag = true;            //退出对话框事件            progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {                @Override                public void onCancel(DialogInterface dialog) {                    flag = false;                }            });            progressDialog.show();        }        @Override        protected  byte[] doInBackground(String... params) {//字符串数组            try {                //创建URL对象,用于访问网络资源                URL url = new URL(params[0]);                //获得HttpUrlConnection对象                HttpURLConnection http = (HttpURLConnection) url.openConnection();                //设置超时时间                http.setConnectTimeout(5000);                //获得总长度                int length = http.getContentLength();                Log.d("=======", length + "");                //为total分配空间                total = new byte[length];                //开始读取数据                int pointer = 0;//已用掉的索引                InputStream is = http.getInputStream();                int real = is.read(current); //读取当前批次的字节并保存到数组中                while(flag && real > 0){                    //如果读取到了字节,则保存到total中                    for(int i = 0; i < real; i ++){                        total[pointer + i] = current[i];                    }                    //指针向后移                    pointer += real;                    //计算进度                    int progress = (int)((double)pointer / length * 100);//先计算出百分比在转换成整型                    //更新进度                    publishProgress(progress, pointer, length);                    //继续读取下一批                    real = is.read(current);                }                //关闭流对象                is.close();                //将获得的所有字节全部返回                return total;            } catch (MalformedURLException e) {                e.printStackTrace();            } catch (IOException e) {                e.printStackTrace();            }            return null;        }        //更新进度条回调        @Override        protected void onProgressUpdate(Integer... values) {            progressDialog.setMessage(                    String.format("已读%d M, 共%d M",//字节为单位                            values[1] / 1024 / 1024, values[2] / 1024 / 1024));//将values[1]赋给第一个%d,第二个同理            progressDialog.setProgress(values[0]);//进度动态提示            Message message001 = handlers.obtainMessage(0x001);            message001.obj=values[0];            handlers.sendMessage(message001);        }        //任务被取消时回调        @Override        protected void onCancelled() {            super.onCancelled();            Toast.makeText(getApplication(),"任务已取消",Toast.LENGTH_SHORT).show();        }        //任务结束后回调        @Override        protected void onPostExecute(byte[] result) {            progressDialog.dismiss();//关闭对话框            Bitmap bitmap = null;            if(flag){                //将获得的字节数组转换成Bitmap图片对象(在安卓中用位图显示图片)                bitmap = BitmapFactory.decodeByteArray(                        result, 0, result.length);                //iv.setImageBitmap(bitmap);                Message message002 = handlers.obtainMessage(0x002);                message002.obj=bitmap;                handlers.sendMessage(message002);            }            flag = false;            //回收内存            if(!flag && !bitmap.isRecycled()){                //bitmap.recycle();            }        }    }}download.xml文件:-----------------------------------<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical">    <ImageView        android:id="@+id/iv"        android:layout_width="match_parent"        android:layout_height="match_parent" />    <ProgressBar        style="?android:attr/progressBarStyleHorizontal"        android:layout_gravity="center_vertical|center_horizontal"        android:id="@+id/progressbar"        android:layout_width="200dp"        android:layout_height="20dp" />    <TextView        android:textColor="#FF0000"        android:id="@+id/textview"        android:layout_below="@id/progressbar"        android:gravity="center_horizontal"        android:textSize="14dp"        android:layout_width="match_parent"        android:layout_height="wrap_content" />    <Button        android:id="@+id/btn"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_alignParentBottom="true"        android:background="@android:color/holo_blue_dark"        android:text="下载图片"        android:textColor="#FFFFFF" /></RelativeLayout>
0 0
原创粉丝点击