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

更新通知必须放到服务中,这样即使切换了界面,下载会一直继续,下面简单讲下流程,
在需要下载的地方,启动服务,并且把下载链接传进来,
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();

    }
}

 

你可能感兴趣的:(安卓)