2.Handler 的实现下载文件ProgressBar进度条和弱引用来优化

方法逻辑跟1Handler差不多 主要就是子线程操作url 下载发送msg给handler进行更新ProgressBar

其他 没什么多说的!直接看代码 这里面绕了一个弯就是更新进度条的时候int类型溢出成负数

案例图片
在这里插入图片描述
MainActivity.java

package com.example.myapplication;

import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;


public class MainActivity extends AppCompatActivity {
    public static final String APPURL = "https://imtt.dd.qq.com/16891/apk/2B96F1332D690C25A4515AB871965DD7.apk";
    public static final int DOWNLOAD_MESSAGE_CODE = 100001;
    public static final int DOWNLOAD_MESSAGE_FAIL_CODE =100002 ;
    private DownloaderHadle handler;
    private TextView textView;
    private ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        textView = (TextView) findViewById(R.id.text1);
        handler = new DownloaderHadle(this);

        /*
        主线程->点击下载 start
        ->发起下载
        ->开启子线程做下载操作
        ->下载过程中完成通知主线程  ->主线程更新进度条
        ->
         */
        findViewById(R.id.btn1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        download(APPURL);
                    }
                }).start();
            }
        });
    }

    private void download(String appurl) {
        try {
            URL url = new URL(appurl);
            URLConnection urlConnection = url.openConnection();
            InputStream inputStream = urlConnection.getInputStream();

            /**
             * 获取文件大小,获取本地下载路径文件命名
             */
            int contentLength = urlConnection.getContentLength();
            String downloadFolderName = Environment.getExternalStorageDirectory()
                    + File.separator + "download" + File.separator;
            File file = new File(downloadFolderName);
            if (!file.exists()) {
                file.mkdir();
            }
            String fileName = downloadFolderName + "aqy.apk";

            File apkFile = new File(fileName);
            if (apkFile.exists()) {
                apkFile.delete();
            }


            byte[] bytes = new  byte[10240];//创建一个字节缓存
            int downloadSize = 0; //进度当前长度默认0  当前进度长度/文件总长度
            int length;
            OutputStream outputStream =new FileOutputStream(fileName);
            while ((length=inputStream.read(bytes))!= -1) {

                outputStream.write(bytes, 0, length);
                downloadSize += length;

                /**
                 更新ui进度条
                 */
                Message message = Message.obtain();
                //这个地方注意downloadSize*100 文件超过20m会出现数据溢出 数值就到不了100%
                message.obj = downloadSize * 100 /contentLength ;
                Log.e("TAG", String.valueOf(downloadSize));
                message.what = DOWNLOAD_MESSAGE_CODE;
                handler.sendMessage(message);

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

        } catch (MalformedURLException e) {
            notifyDownloadFaild();//报错的时候调用这个handler发送消息
            e.printStackTrace();
        } catch (IOException e) {
            notifyDownloadFaild();
            e.printStackTrace();
        }
    }


    /**
     * 自定义的静态handler
     */
    public static class DownloaderHadle extends Handler {
        final WeakReference<MainActivity> mWeakReference;

        DownloaderHadle(MainActivity activity) {
            mWeakReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            MainActivity activity = mWeakReference.get();
            switch (msg.what) {
                case DOWNLOAD_MESSAGE_CODE:
                    activity.textView.setText("当前进度: "+msg.obj+" %");
                    activity.progressBar.setProgress((int) msg.obj);
                    if ((Integer) msg.obj == activity.progressBar.getMax()){
                        activity.textView.setText("下载完成");
                    }
                    break;
            }
        }
    }
    private void notifyDownloadFaild() {
        Message message =Message.obtain();
        message.what = DOWNLOAD_MESSAGE_FAIL_CODE;
        handler.sendMessage(message);
    }

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<Button
    android:id="@+id/btn1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="开始下载"
    />

<ProgressBar
    style="?android:attr/progressBarStyleHorizontal"
    android:id="@+id/progressBar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:max="100"
    android:progress="0"
    android:layout_gravity="center_horizontal"/>


<TextView
    android:id="@+id/text1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="16dp"/>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值