安卓下载更新进度条展示在通知栏

更新通知必须放到服务中,这样即使切换了界面,下载会一直继续,下面简单讲下流程,
在需要下载的地方,启动服务,并且把下载链接传进来,
Intent intent = new Intent(mContext, DownloadService.class);
intent.putExtra("url", apkurl);
mContext.startService(intent);
//这个服务可以直接拿去用,
public class DownloadService extends Service {
    private Context mContext;
    private int preProgress = 0;
    private int NOTIFY_ID = 1000;
    private Notification.Builder builder;
    private NotificationManager notificationManager;
    private String mSavePath;
    private int mProgress;
    private String fileName;
    private int mTotalLength;
    private int mCount;
    private boolean mIsCancel;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mContext = this;
//下载链接,
        if (intent != null) {
            String url = intent.getStringExtra("url");
//开始下载
            startDownLoadApk(url);
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * 下载文件
     */
    private void startDownLoadApk(String url) {
//创建通知栏
        initNotification();
        mIsCancel = false;
        fileName = AppCache.getInstance().getVersionName() + "_" + Utils.getCurrentTime() + ".apk";
        LogUtils.d("", "开始下载");
        ThreadExecutor.executeNormal(() -> {
            try {
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//                      文件保存路径
                    mSavePath = Constants.PATH_APK;
                    File dir = new File(mSavePath);
                    if (!dir.exists()) {
                        dir.mkdir();
                    }

                    // 下载文件
                    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
                    conn.addRequestProperty("Accept-Encoding", "identity");
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    mTotalLength = conn.getContentLength();
                    File apkFile = new File(mSavePath, fileName);
                    FileOutputStream fos = new FileOutputStream(apkFile);

                    mCount = 0;
                    byte[] buffer = new byte[1024];
                    while (!mIsCancel) {
                        LogUtils.d("", "下载中");
                        int numread = is.read(buffer);
                        mCount += numread;
                        // 计算进度条的当前位置
                        mProgress = (int) (((float) mCount / mTotalLength) * 100);
//                            System.out.println("已下载" + length);
                        // 更新进度条
                        updateNotification(mProgress);

                        // 下载完成
                        if (numread < 0) {
                            openAPK("");
                            cancelNotification();
                            break;
                        }
                        fos.write(buffer, 0, numread);
                    }
                    fos.close();
                    is.close();
                    conn.disconnect();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

    }

    /**
     * 下载完成安装apk
     *
     * @param fileSavePath
     */
    private void openAPK(String fileSavePath) {
        File file = new File(mSavePath, fileName);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri data;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//判断版本大于等于7.0
            // "com.ansen.checkupdate.fileprovider"即是在清单文件中配置的authorities
            // 通过FileProvider创建一个content类型的Uri
            data = FileProvider.getUriForFile(LockMsgApp.getInstance().getApplicationContext(), "com.quyan520.quyanandroid.fileprovider", file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);// 给目标应用一个临时授权
        } else {
            data = Uri.fromFile(file);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.setDataAndType(data, "application/vnd.android.package-archive");
        startActivity(intent);
    }


    /**
     * 初始化Notification通知
     */
    @SuppressLint("WrongConstant")
    public void initNotification() {
        String id = "my_channel_01";
        String name = "我是渠道名字";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationChannel mChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_LOW);
            notificationManager.createNotificationChannel(mChannel);
            builder = new Notification.Builder(this)
                    .setContentTitle("")
                    .setSmallIcon(R.mipmap.iv_quyan_logo)
                    .setPriority(NotificationCompat.PRIORITY_HIGH)
                    .setChannelId(id)
                    .setProgress(100, 0, false);
            notificationManager.notify(NOTIFY_ID, builder.build());
        } else {
            builder = new Notification
                    .Builder(this)
                    .setContentTitle("")
                    .setSmallIcon(R.mipmap.iv_quyan_logo)
                    .setPriority(NotificationCompat.PRIORITY_HIGH)
                    .setProgress(100, 0, false);
            notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(NOTIFY_ID, builder.build());
        }
    }

    /**
     * 更新通知
     */
    public void updateNotification(long progress) {
        int currProgress = (int) progress;
        if (preProgress < currProgress) {
            builder.setContentText(progress + "%");
            builder.setProgress(100, (int) progress, false);
            notificationManager.notify(NOTIFY_ID, builder.build());
        }
        preProgress = (int) progress;
    }

    /**
     * 取消通知
     */
    public void cancelNotification() {
        notificationManager.cancel(NOTIFY_ID);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

修行者对666

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值