Android版本强制更新

作者: Poison丶Carson | 来源:发表于2021-06-24 15:12 被阅读0次

    目前的项目之中基本上都会存在版本更新的功能,分为强制更新和推荐更新,其实功能点都是一样的,推荐更新只是增加一个按钮让更新的弹框隐藏掉而已,这里仅记录强制更新的功能

    首先需要跟接口约定,需要判断是否弹出更新弹框

    val isUpdate = VersionUtils.compareVersions("服务端新的版本号","本地版本号")
    if (result.isIsNew && isUpdate) {
        //检查更新
        val checkVersionUtils = CheckVersionUtils(this, result.versionPath
                , result.versionDesc, result.newVersion)
        checkVersionUtils.showUpdateVersion()
    }
    

    这里的isNew为true表示有新版本更新,为false则没有更新,为了防止服务端出错,这里加上了本地的版本号和服务端的版本号进行匹配的字段

    CheckVersionUtils

    public class CheckVersionUtils {
    
        private Context mContext;
        private Dialog mDialog;
        private TextView tvUpdate, tvProgress;
        private ProgressBar progressBar;
        private Logger logger = LoggerFactory.getLogger(CheckVersionUtils.class);
    
        //下载地址
        private String apkUrl;
        private List<String> apkDes;
        private String newVersion;
    
        public CheckVersionUtils(Context context, String apkUrl, List<String> apkDes, String newVersion) {
            this.mContext = context;
            this.apkUrl = apkUrl;
            this.apkDes = apkDes;
            this.newVersion = newVersion;
        }
    
        /**
         * 版本更新弹框
         */
        @SuppressLint("SetTextI18n")
        public void showUpdateVersion() {
            mDialog = new Dialog(mContext, R.style.Teldialog);
            mDialog.setContentView(R.layout.dialog_update_version);
            mDialog.setCanceledOnTouchOutside(false);
            mDialog.setCancelable(false);
            mDialog.show();
    
            tvUpdate = mDialog.findViewById(R.id.tv_update);
            tvProgress = mDialog.findViewById(R.id.tv_progress);
            progressBar = mDialog.findViewById(R.id.progress_bar);
    
            TextView tvVersion = mDialog.findViewById(R.id.tv_version);
            tvVersion.setText("v" + newVersion);
    
            TextView tvDes = mDialog.findViewById(R.id.tv_des);
    
            StringBuffer stringBuffer = new StringBuffer();
            for (int i = 0; i < apkDes.size(); i++) {
                String des = "· " + apkDes.get(i) + "\n";
                stringBuffer.append(des);
            }
            tvDes.setText(stringBuffer);
    
            //立即更新
            tvUpdate.setOnClickListener(view -> {
                tvUpdate.setVisibility(View.GONE);
                tvProgress.setVisibility(View.VISIBLE);
                progressBar.setVisibility(View.VISIBLE);
                initDownload();
            });
        }
    
        /**
         * 下载apk
         */
        private void initDownload() {
            OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
            Request request = new Request.Builder()
                    .url(apkUrl)
                    .get()
                    .build();
    
            okHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    logger.error("apk下载失败:" + e.getMessage());
                    apkUrl = apkUrl.replace("https", "http");
                    initDownload();
                }
    
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    ResponseBody body = response.body();
                    InputStream inputStream = body.byteStream();
                    saveFile(inputStream, Environment.getExternalStorageDirectory() + "/" + "demo.apk", body.contentLength());
                }
            });
        }
    
        /**
         * @param saveFile   存放的地址
         * @param fileLength 文件的长度
         */
        @SuppressLint("SetTextI18n")
        private void saveFile(InputStream inputStream, String saveFile, final long fileLength) {
            long count = 0;
            try {
                FileOutputStream outputStream = new FileOutputStream(new File(saveFile));
                int length = -1;
                byte[] bytes = new byte[1024 * 10];
                while ((length = inputStream.read(bytes)) != -1) {
                    // 写入文件
                    outputStream.write(bytes, 0, length);
                    count += length;
    
                    final long finalCount = count;
                    ((Activity) mContext).runOnUiThread(() -> {
                        // 设置进度条最大值
                        progressBar.setMax((int) fileLength);
                        // 设置下载进度
                        progressBar.setProgress((int) finalCount);
                        // 设置进度文本 (100 * 当前进度 / 总进度)
                        tvProgress.setText((int) (100 * finalCount / fileLength) + "%");
                    });
                }
                inputStream.close();
                outputStream.close();
                ((Activity) mContext).runOnUiThread(() -> {
                    //下载完成,自动安装
                    mDialog.dismiss();
                    ((Activity) mContext).finish();
                    installApk(new File(Environment.getExternalStorageDirectory() + "/" + "demo.apk"));
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        /**
         * 安装apk文件
         *
         * @param apkFile 安装包所在目录
         */
        private void installApk(File apkFile) {
            //判断版本是否在7.0以上
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                Uri apkUri = FileProvider.getUriForFile(mContext,
                        "com.carson.fileprovider", apkFile);
                Intent install = new Intent(Intent.ACTION_VIEW);
                install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                //对目标应用临时授权该Uri所代表的文件
                install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                install.setDataAndType(apkUri, "application/vnd.android.package-archive");
                mContext.startActivity(install);
            } else {
                Intent install = new Intent(Intent.ACTION_VIEW);
                install.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
                install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(install);
            }
        }
    }
    

    需要在manifest中添加处理

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

    xml下的file_paths

    <?xml version="1.0" encoding="utf-8"?>
    <paths>
        <external-path
            name="files_root"
            path="Android/data/com.yugyg.shopkeeper/" />
        <external-path
            name="external_storage_root"
            path="." />
        <root-path
            name="root_path"
            path="" />
    </paths>
    

    贴上dialog

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="316dp"
        android:layout_height="385dp"
        android:background="@mipmap/bg_update"
        android:gravity="center_horizontal"
        android:orientation="vertical"
        android:paddingStart="12dp"
        android:paddingEnd="12dp"
        tools:ignore="MissingDefaultResource">
    
        <TextView
            android:id="@+id/tv_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="56dp"
            android:text="发现新版本"
            android:textColor="@color/color_white"
            android:textSize="16sp" />
    
        <TextView
            android:id="@+id/tv_version"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/tv_title"
            android:layout_marginTop="8dp"
            android:background="@drawable/bg_tv_version"
            android:paddingStart="12dp"
            android:paddingTop="4dp"
            android:paddingEnd="12dp"
            android:paddingBottom="4dp"
            android:text="v1.4"
            android:textColor="@color/color_white"
            android:textSize="12sp" />
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:orientation="vertical">
    
            <android.support.v4.widget.NestedScrollView
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1">
    
                <TextView
                    android:id="@+id/tv_des"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_marginTop="15dp"
                    android:lineSpacingMultiplier="1.5"
                    android:text="111"
                    android:textColor="@color/color_black"
                    android:textSize="12sp" />
            </android.support.v4.widget.NestedScrollView>
    
            <RelativeLayout
                android:layout_width="88dp"
                android:layout_height="32dp"
                android:layout_gravity="center"
                android:layout_marginTop="15dp"
                android:layout_marginBottom="20dp">
    
                <TextView
                    android:id="@+id/tv_update"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:background="@drawable/bg_update_version"
                    android:gravity="center"
                    android:text="立即更新"
                    android:textColor="@color/color_white"
                    android:textSize="12sp" />
    
                <ProgressBar
                    android:id="@+id/progress_bar"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:indeterminateOnly="false"
                    android:mirrorForRtl="true"
                    android:progressDrawable="@drawable/progress_drawable"
                    android:visibility="gone" />
    
                <TextView
                    android:id="@+id/tv_progress"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:text="0%"
                    android:textColor="@color/color_white"
                    android:textSize="12sp"
                    android:visibility="gone" />
            </RelativeLayout>
        </LinearLayout>
    
    </RelativeLayout>
    

    styles

        <style name="Teldialog" parent="@android:style/Theme.Dialog">
            <item name="android:windowBackground">@color/windowTransaction</item>
            <item name="android:windowFrame">@null</item>
            <item name="android:windowNoTitle">true</item>
            <item name="android:windowIsFloating">true</item>
            <item name="android:gravity">bottom</item>
            <item name="android:windowIsTranslucent">true</item>
            <item name="android:windowCloseOnTouchOutside">true</item>
            <item name="android:windowContentOverlay">@null</item>
            <item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
            <item name="android:backgroundDimEnabled">true</item>
        </style>
    

    到此,功能全部实现

    实现效果图 图片.png

    最后贴上版本的比较,在后端进行比较后前端最好也进行一次比较,防止错误的出现,进行容错处理

    /**
     * 如果版本1 大于 版本2 返回true 否则返回fasle 支持 2.2 2.2.1 比较
     * 支持不同位数的比较  2.0.0.0.0.1  2.0 对比
     *
     * @param newVersion 版本服务器版本 " 1.1.2 "
     * @param nowVersion 版本 当前版本 " 1.2.1 "
     * @return ture :需要更新 false : 不需要更新
     */
    public static boolean compareVersions(String newVersion, String nowVersion) {
        //判断是否为空数据
        if (TextUtils.equals(newVersion, "") || TextUtils.equals(nowVersion, "")) {
            return false;
        }
        String[] str1 = newVersion.split("\\.");
        String[] str2 = nowVersion.split("\\.");
        if (str1.length == str2.length) {
            for (int i = 0; i < str1.length; i++) {
                if (Integer.parseInt(str1[i]) > Integer.parseInt(str2[i])) {
                    return true;
                } else if (Integer.parseInt(str1[i]) < Integer.parseInt(str2[i])) {
                    return false;
                } else if (Integer.parseInt(str1[i]) == Integer.parseInt(str2[i])) {
                }
            }
        } else {
            if (str1.length > str2.length) {
                for (int i = 0; i < str2.length; i++) {
                    if (Integer.parseInt(str1[i]) > Integer.parseInt(str2[i])) {
                        return true;
                    } else if (Integer.parseInt(str1[i]) < Integer.parseInt(str2[i])) {
                        return false;
                    } else if (Integer.parseInt(str1[i]) == Integer.parseInt(str2[i])) {
                        if (str2.length == 1) {
                            continue;
                        }
                        if (i == str2.length - 1) {
                            for (int j = i; j < str1.length; j++) {
                                if (Integer.parseInt(str1[j]) != 0) {
                                    return true;
                                }
                                if (j == str1.length - 1) {
                                    return false;
                                }
                            }
                            return true;
                        }
                    }
                }
            } else {
                for (int i = 0; i < str1.length; i++) {
                    if (Integer.parseInt(str1[i]) > Integer.parseInt(str2[i])) {
                        return true;
                    } else if (Integer.parseInt(str1[i]) < Integer.parseInt(str2[i])) {
                        return false;
                    } else if (Integer.parseInt(str1[i]) == Integer.parseInt(str2[i])) {
                        if (str1.length == 1) {
                            continue;
                        }
                        if (i == str1.length - 1) {
                            return false;
                        }
                    }
                }
            }
        }
        return false;
    }
    

    代码传送门

    相关文章

      网友评论

        本文标题:Android版本强制更新

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