Android 应用更新提醒自动跳转安装

ops/2025/3/5 6:27:27/

废话少说,直接上干货

1.首先需要你获取本地的程序版本号

//获取当前版本
public int getAppVersion(Context context) {try {PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);return packageInfo.versionCode;} catch (PackageManager.NameNotFoundException e) {// 应用程序没有找到,这应该不会发生e.printStackTrace();return 0;}
}

2,获取服务器APP版本号

我这里是直接发布到蒲公英平台的,所以我直接调用的蒲公英接口,你们这个发布到哪里就直接调用哪里的接口查询一下最新的版本

3.比较当前版本是否小于服务器的版本,判断是否更新

这里是重点

如果需要更新弹出提示框

我遇到的问题,开始没有弹出提示框,改为子线程中运行

 // 创建一个新的Thread实例Thread thread = new Thread(new Runnable() {@Overridepublic void run() {// 在这里执行你的任务// 这里的代码将在子线程中运行Looper.prepare();AlertDialog.Builder builer = new AlertDialog.Builder(LoginActivity.this) ;builer.setTitle("版本升级");builer.setMessage("软件更新");//当点确定按钮时从服务器上下载 新的apk 然后安装builer.setPositiveButton("确定", (dialog, which) -> downLoadApk(updateInfo.downloadURL));//当点取消按钮时不做任何举动builer.setNegativeButton("取消", (dialogInterface, i) -> {});AlertDialog dialog = builer.create();dialog.show();Looper.loop();}});// 启动线程thread.start();

下载APK方法downLoadApk

protected void downLoadApk(String dowUrl) {//进度条final ProgressDialog pd;pd = new ProgressDialog(this);pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);pd.setMessage("正在下载更新");pd.show();new Thread(){@Overridepublic void run() {try {File file = getFileFromServer(dowUrl, pd);//安装APKinstallAPK(file.getAbsolutePath());pd.dismiss(); //结束掉进度条对话框} catch (Exception e) {}}}.start();
}

获取文件下载方法getFileFromServer

public static File getFileFromServer(String path, ProgressDialog pd) throws Exception{//如果相等的话表示当前的sdcard挂载在手机上并且是可用的if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){URL url = new URL(path);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setConnectTimeout(5000);//获取到文件的大小pd.setMax(conn.getContentLength());InputStream is = conn.getInputStream();File file = new File(Environment.getExternalStorageDirectory(), "爱智牧.apk");FileOutputStream fos = new FileOutputStream(file);BufferedInputStream bis = new BufferedInputStream(is);byte[] buffer = new byte[1024];int len ;int total=0;while((len =bis.read(buffer))!=-1){fos.write(buffer, 0, len);total+= len;//获取当前下载量pd.setProgress(total);}fos.close();bis.close();is.close();return file;}else{return null;}
}

下载后跳转安装的方法installAPK

    /*** * @param Path apk路径*/public void installAPK(String Path) {File apkFile = new File(Path);if (!apkFile.exists()){return;}Intent intent = new Intent(Intent.ACTION_VIEW);
//      安装完成后,启动appintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);// Android 版本在7.0以上if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {boolean  hasInstallPermission = this.getPackageManager().canRequestPackageInstalls();if (!hasInstallPermission) {//请求安装未知应用来源的权限ActivityCompat.requestPermissions((Activity) this, new String[]{Manifest.permission.REQUEST_INSTALL_PACKAGES}, 6666);}}Uri apkUri = FileProvider.getUriForFile(this, "包名.fileprovider", apkFile);intent.setDataAndType(apkUri, "application/vnd.android.package-archive");this.startActivity(intent);}else {Log.e("安装","-----333----");Uri uri = Uri.parse("file://" + apkFile.toString());intent.setDataAndType(uri, "application/vnd.android.package-archive");}LoginActivity.this.startActivity(intent);}

说明:因为版本的要求,我们这里获取安装路径需要做一些配置,要不下载apk后不会自动跳转到安装界面。

1.在Android.xml中配置相关权限

这个可能还不够,我在我的项目中只添加了这两个,其他的可以百度查询一下。

<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
<!-- 安装未知来源权限-->
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />

2.在Android.xml中配置provider

<providerandroid:name="androidx.core.content.FileProvider"android:authorities="包名.fileprovider"android:grantUriPermissions="true"tools:replace="android:authorities"android:exported="false"><meta-dataandroid:name="android.support.FILE_PROVIDER_PATHS"android:resource="@xml/provider_paths" />
</provider>

3.在res/xml中新建文件file_paths.xml

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

配置好这些才能自动跳转到安装界面


http://www.ppmy.cn/ops/15632.html

相关文章

单例设计模式c++

什么是单例模式&#xff1f; 单例模式指在整个系统生命周期里&#xff0c;保证一个类只能产生一个实例&#xff0c;确保该类的唯一性。 单例模式分类 单例模式可以分为懒汉式和饿汉式&#xff0c;两者之间的区别在于创建实例的时间不同&#xff1a; 懒汉式&#xff1a;指系…

vue实现光标插入模板和删除指定模板内容

需求&#xff1a; 文本可插入模板文字&#xff1b;同时在“%虚拟机名称%”后一个%删除,会将“%虚拟机名称%”选中删除 以下代码可以直接复制使用&#xff1a; <template><div><div><b>需求&#xff1a;</b> <br> 文本可插入模板文字&am…

FinalShell 安装 及使用教程

一 简介&#xff1a; FinalShell 是一款免费的国产的集 SSH 工具、服务器管理、远程桌面加速的良心软件&#xff0c;同时支持 Windows,macOS,Linux&#xff0c;它不单单是一个 SSH 工具&#xff0c;完整的说法应该叫一体化的的服务器&#xff0c;网络管理软件&#xff0c;在很…

深度学习中的黑科技:自监督学习(Self-Supervised Learning)

在人工智能领域&#xff0c;深度学习已成为推动技术革新的核心力量。然而&#xff0c;深度学习的一个重要瓶颈是对大量标记数据的依赖性。在这个背景下&#xff0c;自监督学习(Self-Supervised Learning, SSL)作为一种新兴的学习范式&#xff0c;越来越受到研究者的关注。自监督…

Pandas 2.2 中文官方教程和指南(九·二)

比较类似数组的对象 当将 pandas 数据结构与标量值进行比较时&#xff0c;您可以方便地执行逐元素比较&#xff1a; In [65]: pd.Series(["foo", "bar", "baz"]) "foo" Out[65]: 0 True 1 False 2 False dtype: boolIn …

【Xilinx】时序约束学习 TIMING-1: 时钟修改块上的时钟波形无效

在 <cell_type> 输出 <pin_name> 上指定的时钟 <clock_name> 的时钟波形无效&#xff0c; 与时钟修改块 (CMB) 设置不匹配。该时钟波形为 <VALUE>。期望的波形为 <VALUE>。 描述 Vivado Design Suite 会根据 CMB 设置和传入主时钟的特性&#xf…

ArrayList

一.简介 在集合框架中&#xff0c;ArrayList是一个普通的类&#xff0c;实现了List接口&#xff0c;具体框架如下 说明&#xff1a; 1.ArrayList是以泛型方式实现的&#xff0c;使用时必须先实例化 2.ArrayList实现了RandomAccess接口&#xff0c;表明ArrayList支持随机访问…

在windows系统中安装kafka配置全步骤记录

在windows系统中安装kafka配置全步骤记录 提示&#xff1a;这里可以添加系列文章的所有文章的目录&#xff0c;目录需要自己手动添加 例如&#xff1a;第一章 Python 机器学习入门之pandas的使用 提示&#xff1a;写完文章后&#xff0c;目录可以自动生成&#xff0c;如何生成可…