Android之AsyncTask的使用(二)之文件下载

声明: 本人菜鸟一枚, 本博客是本人自学的内容, 适用于初学者, 不喜勿喷, 谢谢大家


通过上一篇博客我们学习到了AsyncTask的主要作用, 那今天就写一个实际的例子: 文件下载

下载案例

在开始下载代码之前, 我们需要在清单文件中先加上权限!

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

DownloadActivity .java


public class DownloadActivity extends AppCompatActivity {
    private ProgressBar progressBar;
    private ImageView imageView;

    private static final int FILE_SIZE = 0;
    private static final int DOWNLOAD_PROGRESS = 1;
    private static final int DOWNLOAD_SUCCESS = 2;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        imageView = (ImageView) findViewById(R.id.imageView);

    }

    public void downloadClick(View view){
        new DownloadAsyncTas(this).execute("http://tupian.enterdesk.com/2013/mxy/10/12/5/1.jpg");
    }

    private static class DownloadAsyncTas extends AsyncTask<String, Integer, Integer>{

        private DownloadActivity activity;

        public DownloadAsyncTas(DownloadActivity activity) {
            this.activity = activity;
        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            //先将其进度设置为0
            activity.progressBar.setProgress(0);


        }

        @Override
        protected Integer doInBackground(String... params) {

            //完成下载任务
            String s = params[0];//这是从execute方法中传过来的参数, 即下载的地址
            try {
                URL url = new URL(s);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                int size = conn.getContentLength();//获取到最大值之后设置到进度条的MAX
                publishProgress(FILE_SIZE, size);

                //开始下载
                byte[] bytes = new byte[10];//为方便测试故将其设置较小
                int len = -1;
                InputStream in = conn.getInputStream();
                FileOutputStream out = new FileOutputStream(
                        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + "img.jpg");
                while( (len = in.read(bytes)) != -1 ){
                    out.write(bytes, 0, len);
                    publishProgress(DOWNLOAD_PROGRESS, len);
                    out.flush();
                }
                out.close();
                in.close();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return DOWNLOAD_SUCCESS;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);

            switch (values[0]){
                case FILE_SIZE:
                    activity.progressBar.setMax(values[1]);
                    break;
                case DOWNLOAD_PROGRESS:
                    activity.progressBar.incrementProgressBy(values[1]);
                    break;
            }

        }

        @Override
        protected void onPostExecute(Integer integer) {
            super.onPostExecute(integer);
            if(integer == DOWNLOAD_SUCCESS){
                activity.imageView.setImageURI(Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + "img.jpg"));
            }


        }
    }

}

效果图:
这里写图片描述

AsyncTask准则

  1. AsyncTask的实例必须在UI 线程中创建
  2. execute方法必须在UI线程中调用
  3. 不要手动的调用onPreExecute, doInBackground, onProgressUpdate, onPostExecute这几个方法
  4. 该Task只能执行一次, 否则多次调用会出现异常
  5. AsyncTask不能完全取代线程. 在些较为复杂或者后台反复执行的逻辑就可能需要线程和Handler来实现了

座右铭: 少说话, 多做事

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值