应用内下载更新app适配Ansroid7.0,8.0

应用中使用的下载更新app的方式
1.使用Okhttp进行apk文件下载
module的gradle中加入下面两行,项目依赖Okhttp
在这里插入图片描述
2.访问文件适配android 7.0及以上版本
在Manifest中添加:
在这里插入图片描述
3.res资源文件下创建目录xml:
下载文件路径为/storage/emulated/0/download/
表明访问外部存储,路径为/storage/emulated/0/download/
4.写一个帮助类DownloadUtil下载apk文件

public class DownloadUtil {
    private static DownloadUtil downloadUtil;
    private final OkHttpClient okHttpClient;
    public static DownloadUtil get() {
        if (downloadUtil == null) {
            downloadUtil = new DownloadUtil();
        }
        return downloadUtil;
    }

    private DownloadUtil() {
        okHttpClient = new OkHttpClient();
    }

    /**
     * @param url 下载连接
     * @param saveDir 储存下载文件的SDCard目录
     * @param listener 下载监听
     */
    public void download(final String url, final String saveDir, final String apkName, final OnDownloadListener listener) {
        Request request = new Request.Builder().url(url).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 下载失败
                listener.onDownloadFailed();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                // 储存下载文件的目录
                String savePath = isExistDir(saveDir);
                try {
                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    File file = new File(savePath, apkName);
                    Log.i("Download", "onResponse: ========" + file.getAbsolutePath());
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        // 下载中
                        listener.onDownloading(progress);
                    }
                    fos.flush();
                    // 下载完成
                    listener.onDownloadSuccess();
                } catch (Exception e) {
                    e.printStackTrace();
                    listener.onDownloadFailed();
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                    }
                }
            }
        });
    }

    /**
     * @param saveDir
     * @return
     * @throws IOException
     * 判断下载目录是否存在
     */
    private String isExistDir(String saveDir) throws IOException {
        // 下载位置
        File downloadFile = new File(saveDir);
        if (!downloadFile.mkdirs()) {
            downloadFile.createNewFile();
        }
        String savePath = downloadFile.getAbsolutePath();
        return savePath;
    }

    /**
     * @param url
     * @return
     * 从下载连接中解析出文件名
     */
    @NonNull
    private String getNameFromUrl(String url) {
        return url.substring(url.lastIndexOf("/") + 1);
    }

    public interface OnDownloadListener {
        /**
         * 下载成功
         */
        void onDownloadSuccess();
        /**
         * @param progress
         * 下载进度
         */
        void onDownloading(int progress);
        /**
         * 下载失败
         */
        void onDownloadFailed();
    }
}

5.新建一个Service将下载任务放在后台进行
由于此Service中要执行长时间耗时任务,因此继承IntentService并在handleIntent方法中进行耗时操作
在这里插入图片描述

6.在通知栏显示下载进度:
在这里插入图片描述
注意:在Android8.0系统以后添加了NotificationChannel(通知渠道),用来允许您为要显示的每种通知类型创建用户可自定义的渠道。如果不设置channelId和channelName,android8.0以后将在通知栏不显示此通知。
在这里插入图片描述
更新下载进度:
downloading方法中使用 updateProgress更新下载进度
在这里插入图片描述
注意:downloading方法中更新加了一个判断:
在这里插入图片描述
这是由于下载过程中如果不断刷新通知会造成通知栏卡顿,所以每次progress增加1才通知Notification去刷新界面。
7.下载完成之后安装apk:
在Android7.0版本以上添加了文件访问适配
在Android8.0版本以上添加了打开允许安装未知应用权限
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_32365409/article/details/82787221