思路是:获取服务器最新版本,和手机当前版本比较,大于当前版本就下载更新,否则就什么都不做
具体思路请参看我另一篇博客:https://blog.youkuaiyun.com/yijiaodingqiankun/article/details/83271042
//获取手机中APP当前版本 public int getVersion() { try { //获取包管理器 PackageManager packageManager = getPackageManager(); //显示安装包信息 PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(), 0); //获取版本名称 String versionName = packageInfo.versionName; //获取版本号 int versionCode = packageInfo.versionCode; return versionCode; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return 0; }
//下载apk的方法 private void downloadApk(String versionUrl) { // (1)通过getSystemService获取DownLoadManager。 DownloadManager systemService = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); //( 2)初始化DownLoadManager的Request,构建下载请求 DownloadManager.Request request = new DownloadManager.Request(Uri.parse(BASE_URL + versionUrl)); // Log.e("downloadApk: ",BASE_URL +versionUrl ); //设置文件保存路径 request.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, "app-release.apk"); //(3)调用DownLoadManager的enqueue异步发起请求,该方法返回值为标识当前下载任务的id,即downloadId long downloadId = systemService.enqueue(request); // 4)当下载完成后,系统会发出条件为android.intent.action.DOWNLOAD_COMPLETE的广播,我们可以自定义广播接受器,然后在onReceive中处理下载完成的逻辑即可。 }
/** * Created by DELL zhanghuirong on 2020/1/26. */ //apk安装接收器 public class ApkInstallReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) { long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1); //安装apk installApk(context, downloadId); } } /** * 安装APK */ private void installApk(Context context, long downloadId) { DownloadManager downloadManager = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE); Uri uriForDownloadedFile = downloadManager.getUriForDownloadedFile(downloadId); if (uriForDownloadedFile != null) { Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.setDataAndType(uriForDownloadedFile, "application/vnd.android.package-archive"); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); }else { ToastUtils.makeText("下载失败"); } } // // private void removeFile() { // String filePath = // if (filePath != null) { // File downloadfile = new File(filePath); // if (downloadfile != null && downloadfile.exists()) { //// 删除之前先判断用户是否已经安装,安装了才能删除 // if (hasSDK()) { // downloadfile.delete(); // Log.e("removeFile: ","已删除" ); // } // } // } // } }
在清单文件添加如下代码
<!--安装apk的广播接收器--> <receiver android:name=".bean.ApkInstallReceiver"> <intent-filter> <action android:name="android.intent.action.DOWNLOAD_COMPLETE"/> </intent-filter> </receiver>