下载异步任务类

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import com.cihi.R;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;

/**
 * @author xly
 * 下载的异步任务类
 */
public class DownLoaderTask extends AsyncTask<Void, Integer, Long> {
    private URL url;                //文件链接地址
    private File file;                //下载到本地的文件
    private ProgressDialog dialog;    //下载进度的ProgressDialog
    private int progress;            //下载进度
    private ProgressReportingOutputStream outputStream;
    private Context context;
    
    public DownLoaderTask(String url, String filePath, Context context) {
        super();
        if (context != null) {
            dialog = new ProgressDialog(context);
            this.context = context;
        } else {
            dialog = null;
        }
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            try {
                this.url = new URL(url);
                String fileName = new File(this.url.getFile()).getName();
                if (!new File(filePath).exists()) {    //如果保存文件的文件夹不存在
                    new File(filePath).mkdirs();    //创建文件夹
                }
                this.file = new File(filePath, fileName);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
        }
    }
    
    @Override
    protected void onPreExecute() {
        if (dialog != null) {
            dialog.setTitle(R.string.downloading);
            dialog.setMessage("请保持网络连接");
            dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            dialog.setOnCancelListener(new OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    cancel(true);
                }
            });
            dialog.show();
        }
        super.onPreExecute();
    }
    
    @Override
    protected Long doInBackground(Void... params) {
        return download();
    }
    
    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        if (dialog == null) {
            return;
        }
        if (values.length > 1) {
            int countLength = values[1];
            if (countLength == -1) {
                dialog.setIndeterminate(true);
            } else {
                dialog.setMax(countLength);
            }
        } else {
            dialog.setProgress(values[0].intValue());
        }
    }
    
    @Override
    protected void onPostExecute(Long result) {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        if (isCancelled()) {
            return;
        }
        if (CheckUpdate.getUpdate()) {
            CheckUpdate.update(context);
        }
        ///下载完成后,开始解压缩的提醒///
        super.onPostExecute(result);
    }
    
    private long download() {
        URLConnection connection = null;
        int byteCopy = 0;
        try {
            connection = this.url.openConnection();        //打开文件地址的链接
            int length = connection.getContentLength();    //读取文件大小
            if (this.file.exists() && length == this.file.length()) {
                Log.d("DownLoaderTask", this.file.getName() + " 文件已存在");
                return 01;
            }
            outputStream = new ProgressReportingOutputStream(file);
            publishProgress(0, length);
            byteCopy = copy(connection.getInputStream(), outputStream);
            if (byteCopy != length && length != -1) {
                Log.d("DownLoaderTask", "download complete bytescopy " + byteCopy + ", length" + length);
            }
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return byteCopy;
    }
    
    private int copy(InputStream input, OutputStream output) {
        byte[] buffer = new byte[1024 * 8];
        BufferedInputStream in = new BufferedInputStream(input, 1024 * 8);
        BufferedOutputStream out = new BufferedOutputStream(output, 1024 * 8);
        int count = 0, n = 0;
        try {
            while ((n = in.read(buffer, 0, 1024 * 8)) != -1) {
                out.write(buffer, 0, n);
                count += n;
            }
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e2) {
                e2.printStackTrace();
            }
            try {
                in.close();
            } catch (IOException e2) {
                e2.printStackTrace();
            }
        }
        return count;
    }

    private final class ProgressReportingOutputStream extends FileOutputStream {
        public ProgressReportingOutputStream(File file) throws FileNotFoundException {
            super(file);
        }
        @Override
        public void write(byte[] buffer, int byteOffset, int byteCount)
                throws IOException {
            super.write(buffer, byteOffset, byteCount);
            progress += byteCount;
            publishProgress(progress);
        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值