Handler 实现下载文件并更新进度条

public class DownLoadActivity extends Activity {

    private Handler handler;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download);

        final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);

        //主线程 点击按钮 发起下载 开启子线程做下载 下载过程中通知主线程 主线程更新进度条

        findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            download("http://download.sj.qq.com/upload/connAssitantDownload/upload/MobileAssistant_1.apk");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();

            }
        });

        handler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);

                switch (msg.what){
                    case 100001 :
                        progressBar.setProgress((Integer) msg.obj);
                        break;
                }
            }
        };

    }

    private void download(String appUrl) throws IOException {
        URL url = new URL(appUrl);
        URLConnection urlConnection = url.openConnection();
        InputStream inputStream = urlConnection.getInputStream();

        //获取文件的总长度
        //
        int contentLength = urlConnection.getContentLength();
        String downloadFolderName = Environment.getExternalStorageDirectory() + File.separator + "imooc" + File.separator;

        File file = new File(downloadFolderName);
        if(!file.exists()){
            file.mkdir();
        }

        String fileName = downloadFolderName + "imooc.apk";
        File apkFile = new File(fileName);
        if(apkFile.exists()){
            apkFile.delete();
        }


        int downloadSize = 0;
        byte[] bytes = new byte[1024];

        int length = 0;

        OutputStream outputStream = new FileOutputStream(fileName);
        while((length = inputStream.read(bytes)) != -1){
            outputStream.write(bytes, 0 , length);
            downloadSize += length;

            Message message = Message.obtain();
            message.obj = downloadSize * 100 / contentLength;
            message.what = 100001;
            handler.sendMessage(message);
        }

        inputStream.close();
        outputStream.close();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值