美文网首页
Android版本升级(适配Android10)

Android版本升级(适配Android10)

作者: 移动端_小刚哥 | 来源:发表于2019-11-15 16:03 被阅读0次

版本升级分为两部分--下载和安装

一、下载

    /*版本升级*/
    public static void versionUpdate(Context context, UpdateDao updateDao) {
        if (updateDao != null && updateDao.getData() != null) {
            if (updateDao.getData().getFlag().equals("1") == true) {//强制升级
                HashMap<String, Object> map = new HashMap<>();
                map.put("context", context);
                map.put("updateDao", updateDao);
                handler.sendMessage(handler.obtainMessage(11, map));
            } else {//非强制升级
                HashMap<String, Object> map = new HashMap<>();
                map.put("context", context);
                map.put("updateDao", updateDao);
                handler.sendMessage(handler.obtainMessage(22, map));
            }
        }
    }


    static void downFile(final String url, final Context context) {
//        pBar.show();
        new Thread() {
            public void run() {
                String filePath = "";
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    filePath = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getPath() + "/zuhuCRM.apk";
                } else {
                    filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/updateApkFile/zuhuCRM.apk";
                }
                File apkFile = new File(filePath);
                if (apkFile.exists() == true) {
                    apkFile.delete();//如果存在就删掉
                    Log.d("", "删除已经存在的安装包");
                }
//                String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/updateApkFile/";
                Log.d("下载文件路径为", filePath);
                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    request.setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS, "zuhuCRM.apk");
                } else {
                    request.setDestinationInExternalPublicDir("/updateApkFile/", "zuhuCRM.apk");
                }
                DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
                long downloadId = downloadManager.enqueue(request);
                Timer timer = new Timer(true);
                TimerTask timerTask = new TimerTask() {
                    @Override
                    public void run() {
                        HashMap<String, Object> map = new HashMap<>();
                        map.put("downloadManager", downloadManager);
                        map.put("downloadId", downloadId);
                        map.put("timer", timer);
                        map.put("context", context);
                        handler.sendMessage(handler.obtainMessage(33, map));
                    }
                };
                timer.schedule(timerTask, 100, 200);
            }
        }.start();
    }


    /*获取下载进度*/
    static int getDownloadPercent(long downloadId, DownloadManager downloadManager) {
//            String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/updateApkFile/zuhuCRM.apk";
//            File apkFile = new File(filePath);
//            long fileLength = apkFile.length();
//
//            Log.d("","文件大小为"+String.valueOf(fileLength));
        DownloadManager.Query query = new DownloadManager.Query().setFilterById(downloadId);
        Cursor cursor = downloadManager.query(query);
        if (cursor.moveToFirst()) {
            int downloadByTestIdx = cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
            int totalByTestIdx = cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
            long totalBytes = cursor.getLong(totalByTestIdx);
            long downloadBytes = cursor.getLong(downloadByTestIdx);
            int jinduFlo = Math.round(downloadBytes * 100 / totalBytes);
            Log.d("下载进度:totalBytes=", String.valueOf(totalBytes) + " downloadBytes=" + String.valueOf(downloadBytes) + " 进度=" + String.valueOf(jinduFlo) + "%");
            if (jinduInt <= 10) {
                jinduInt += 5;
            } else if (jinduInt <= 30) {
                jinduInt += 2;
            } else if (jinduInt <= 50) {
                jinduInt += 3;
            } else if (jinduInt <= 80) {
                jinduInt += 2;
            } else if (jinduInt <= 95) {
                if (jinduFlo >= 100) {
                    jinduInt += 3;
                } else {
                    jinduInt += 1;
                }
            } else if (jinduInt <= 100) {
                if (jinduFlo >= 100) {
                    jinduInt += 1;
                } else {//如果这个时候还没有下载完那么进度就不增加了
                }
            }
            if (jinduInt > 100) {
                jinduInt = 100;
            }
            return jinduInt;
        }
        return 0;
    }

hander为

    static int jinduInt = 0;
    static boolean isDownloadSuccAndroid10 = false;
    static ProgressDialog pBar;
    static boolean isShowingUpdate = false;
    static UpdateDialog updateDialog;
    static Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 11) {//版本升级提示(非强制升级)
                HashMap<String, Object> map = (HashMap<String, Object>) msg.obj;
                Context context = (Context) map.get("context");
                UpdateDao updateDao = (UpdateDao) map.get("updateDao");
                String verName = Utils.getVersionName(context);
                AlertDialog alertDialog2 = new AlertDialog.Builder(context)
                        .setTitle("软件更新")
                        .setMessage("当前版本:" + verName + ", 发现新版本")
                        .setPositiveButton("更新", new DialogInterface.OnClickListener() {//添加"Yes"按钮
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                Log.d("click", "点击确定按钮");
                                isShowingUpdate = false;
                                pBar = new ProgressDialog(context);
                                pBar.setTitle("正在下载");
                                pBar.setMessage("请稍候...");
                                pBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
//                                    downFileAndroid10(updateDao.getData().getUrl(), context);
//                                } else {
//                                    downFile(updateDao.getData().getUrl(), context);
//                                }
                                downFile(updateDao.getData().getUrl(), context);
                            }
                        })
                        .create();
                //点击背景不消失
                alertDialog2.setCanceledOnTouchOutside(false);
                if (isShowingUpdate == false) {
                    isShowingUpdate = true;
//                    alertDialog2.show();
                }
                //正在展示升级提示框
                if (updateDialog != null && updateDialog.isShowing()) {
                } else {//当前没有在展示升级提示框
                    updateDialog = new UpdateDialog(context);
                    updateDialog.feiqiangzhigengxin();
                    updateDialog.setZuixinbanben("最新版本:V" + verName);
                    updateDialog.setXinbanbendaxiao("新版本大小:" + updateDao.getData().getFileSize() + "M");
                    updateDialog.setGengxinneirong(updateDao.getData().getUpdateContent());
                    updateDialog.setXiaochachaListen(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            updateDialog.cancel();
                        }
                    });
                    updateDialog.setCancneListen(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            updateDialog.cancel();
                        }
                    });
                    updateDialog.setUpdateListen(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                            } else {
                                String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/updateApkFile/zuhuCRM.apk";
                                File apkFile = new File(filePath);
                                if (apkFile.exists() == true) {
                                    apkFile.delete();//如果存在就删掉
                                    Log.d("", "删除已经存在的安装包");
                                }
                            }
                            updateDialog.setXiazaizhong();
//                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
//                                downFileAndroid10(updateDao.getData().getUrl(), context);
//                            } else {
//                                downFile(updateDao.getData().getUrl(), context);
//                            }
                            downFile(updateDao.getData().getUrl(), context);
                        }
                    });
                    updateDialog.show();
                }

            } else if (msg.what == 22) {//版本升级提示(强制升级)
                HashMap<String, Object> map = (HashMap<String, Object>) msg.obj;
                Context context = (Context) map.get("context");
                UpdateDao updateDao = (UpdateDao) map.get("updateDao");
                String verName = Utils.getVersionName(context);
                AlertDialog alertDialog2 = new AlertDialog.Builder(context)
                        .setTitle("软件更新")
                        .setMessage("当前版本:" + verName + ", 发现新版本")
                        .setPositiveButton("更新", new DialogInterface.OnClickListener() {//添加"Yes"按钮
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                Log.d("click", "点击确定按钮");
                                isShowingUpdate = false;
                                pBar = new ProgressDialog(context);
                                pBar.setTitle("正在下载");
                                pBar.setMessage("请稍候...");
                                pBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
//                                    downFileAndroid10(updateDao.getData().getUrl(), context);
//                                } else {
//                                    downFile(updateDao.getData().getUrl(), context);
//                                }
                                downFile(updateDao.getData().getUrl(), context);
                            }
                        })
                        .setNegativeButton("暂不更新", new DialogInterface.OnClickListener() {//添加取消
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                Log.d("click", "点击取消按钮");
                                isShowingUpdate = false;
                            }
                        })
                        .create();
                //点击背景不消失
                alertDialog2.setCanceledOnTouchOutside(false);
                if (isShowingUpdate == false) {
                    isShowingUpdate = true;
//                    alertDialog2.show();
                }
                //正在展示升级提示框
                if (updateDialog != null && updateDialog.isShowing()) {
                } else {//当前没有在展示升级提示框
                    updateDialog = new UpdateDialog(context);
                    updateDialog.setZuixinbanben("最新版本:V" + verName);
                    updateDialog.setXinbanbendaxiao("新版本大小:" + updateDao.getData().getFileSize() + "M");
                    updateDialog.setGengxinneirong(updateDao.getData().getUpdateContent());
                    updateDialog.setXiaochachaListen(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            updateDialog.cancel();
                        }
                    });
                    updateDialog.setCancneListen(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            updateDialog.cancel();
                        }
                    });
                    updateDialog.setUpdateListen(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                            } else {
                                String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/updateApkFile/zuhuCRM.apk";
                                File apkFile = new File(filePath);
                                if (apkFile.exists() == true) {
                                    apkFile.delete();//如果存在就删掉
                                    Log.d("", "删除已经存在的安装包");
                                }
                            }
                            updateDialog.setXiazaizhong();
//                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
//                                downFileAndroid10(updateDao.getData().getUrl(), context);
//                            } else {
//                                downFile(updateDao.getData().getUrl(), context);
//                            }
                            downFile(updateDao.getData().getUrl(), context);
                        }
                    });
                    updateDialog.show();
                }

            } else if (msg.what == 33) {
                HashMap<String, Object> map = (HashMap<String, Object>) msg.obj;
                Context context = (Context) map.get("context");
                Timer timer = (Timer) map.get("timer");
                DownloadManager downloadManager;
                long downloadId;
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
//                    downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
//                    downloadId = 0;
//                } else {
//                    downloadManager = (DownloadManager) map.get("downloadManager");
//                    downloadId = (long) map.get("downloadId");
//                }
                downloadManager = (DownloadManager) map.get("downloadManager");
                downloadId = (long) map.get("downloadId");
                int jindu = getDownloadPercent(downloadId, downloadManager);
                if (jindu >= 100) {//下完了
                    if (timer != null) {
                        timer.cancel();
                    }
//                    if (pBar!=null){
//                        pBar.cancel();
//                    }
                    if (updateDialog != null) {
                        updateDialog.cancel();
                    }
                    installApk(context);//安装

                } else {//没下完呢,显示下载进度
//                    java.text.DecimalFormat myformat=new java.text.DecimalFormat("0.00");
//                    String str = myformat.format(jindu);
//                    if (pBar!=null){
//                        pBar.setMessage(String.valueOf("下载进度:"+str+"%"));
//                    }
                    if (updateDialog != null) {
                        updateDialog.setGengxinjindu((int) jindu);
                    }

                }


            }
        }
    };

二、安装

    /*安装下载好的apk包*/
    static void installApk(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            //可以安装沙盒内的apk包
            //apk文件完整路径
            File apkFile;
//            String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/updateApkFile/zuhuCRM.apk";
            String filePath = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS + "/zuhuCRM.apk").getAbsolutePath();
            apkFile = new File(filePath);
            Log.d("apk包大小=", String.valueOf(apkFile.length()));
            if (Build.VERSION.SDK_INT >= 24) {//android 7.0之后 Android 10之前
                Log.d("更新文件大小", String.valueOf(apkFile.length()));
                Log.d("文件是否存在", String.valueOf(apkFile.exists()));
                Uri uri = FileProvider.getUriForFile(context, "im.yixin.fileprovider", apkFile);
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setAction(Intent.ACTION_INSTALL_PACKAGE);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//7.0以后,系统要求授予临时uri读取权限,安装完毕以后,系统会自动收回权限,该过程没有用户交互
                intent.setDataAndType(uri, "application/vnd.android.package-archive");
                context.startActivity(intent);
            } else {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(Uri.fromFile(apkFile),
                        "application/vnd.android.package-archive");
                context.startActivity(intent);
            }
        } else {
            //apk文件完整路径
            File apkFile;
            String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/updateApkFile/zuhuCRM.apk";
            apkFile = new File(filePath);
            Log.d("apk包大小=", String.valueOf(apkFile.length()));
            if (Build.VERSION.SDK_INT >= 24) {//android 7.0之后 Android 10之前
                Log.d("更新文件大小", String.valueOf(apkFile.length()));
                Log.d("文件是否存在", String.valueOf(apkFile.exists()));
                Uri uri = FileProvider.getUriForFile(context, "im.yixin.fileprovider", apkFile);
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setAction(Intent.ACTION_INSTALL_PACKAGE);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//7.0以后,系统要求授予临时uri读取权限,安装完毕以后,系统会自动收回权限,该过程没有用户交互
                intent.setDataAndType(uri, "application/vnd.android.package-archive");
                context.startActivity(intent);
            } else {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(Uri.fromFile(apkFile),
                        "application/vnd.android.package-archive");
                context.startActivity(intent);
            }
        }
        //让app退出
        ArrayList arrayList = new ArrayList();
        arrayList.get(100);

    }

还需要在res中新建xml文件夹,并新建filepaths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path
        name="external-path"
        path="." />
</paths>

另外修改AndroidManifest.xml

    <application
        android:name=".CallRecorder.App"
        android:allowBackup="true"
        android:icon="@mipmap/crm_icon"
        android:label="@string/app_name"
        android:networkSecurityConfig="@xml/network_security_config"
        android:roundIcon="@mipmap/crm_icon"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        >



        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="im.yixin.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true"
            >
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/filepaths"
                />
        </provider>

</application>

⚠️这里的im.yixin.fileprovider要和代码中一样

参考文章
https://blog.csdn.net/yozhangxin/article/details/78913790
https://blog.csdn.net/qq_26608277/article/details/69787604
https://blog.csdn.net/qq_31450487/article/details/73614251
https://www.jianshu.com/p/ae9b3ee1f2ce

相关文章

网友评论

      本文标题:Android版本升级(适配Android10)

      本文链接:https://www.haomeiwen.com/subject/fwdsictx.html