Android如何实现APP自动更新

先来看看要实现的效果图:


对于安卓用户来说,手机应用市场说满天飞可是一点都不夸张,比如小米,魅族,百度,360,机锋,应用宝等等,当我们想上线一款新版本APP时,先不说渠道打包的麻烦,单纯指上传APP到各大应用市场的工作量就已经很大了,好不容易我们把APP都上传完了,突然发现一个会导致应用闪退的小Bug,这时那个崩溃啊,明明不是很大的改动,难道我们还要再去重新去把各大应用市场的版本再上传更新一次?相信我,运营人员肯定会弄死你的!!

有问题,自然就会有解决问题的方案,因此我们就会想到如果在APP里内嵌自动更新的功能,那么我们将可以省去很多麻烦,当然关于这方面功能的第三方SDK有很多。

好了,言归正传,今天我们自己来实现下关于APP自动更新。

流程其实并不复杂:当用户打开APP的时候,我们让APP去发送一个检查版本的网络请求,或者利用服务端向APP推送一个透传消息来检查APP的版本,如果当前APP版本比服务器上的旧,那么我们就提醒用户进行下载更新APP,当然在特定的情况下,我们也可以强制的让用户去升级,当然这是很不友好的,尽可能的减少这样的做法。

好了,来梳理下流程,首先既然是一个APP的更新,那么我们就需要去下载新的APP,然后我们需要一个通知来告诉用户当前的下载进度,再来当APP安装包下载完成后,我们需要去系统的安装程序来对APP进行安装更新。

知识点:

下载:异步HTTP请求文件下载,并监听当前下载进度(这里我采用了okhttp)

通知:Notification(具体用法请自行翻阅API文档)

安装:Intent (具体用法请自行翻阅API文档)

来看下具体实现代码:

我们需要一个后台服务来支撑App的下载

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v7.app.NotificationCompat;
 
import com.fangku.commonlibrary.utils.StorageUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
 
import java.io.File;
 
import okhttp3.Call;
 
/**
 * 自动下载更新apk服务
 * Create by: chenwei.li
 * Date: 2016-08-14
 * time: 09:50
 * Email: lichenwei.me@foxmail.com
 */
public class DownloadService extends Service {
 
 private String mDownloadUrl;//APK的下载路径
 private NotificationManager mNotificationManager;
 private Notification mNotification;
 
 
 @Override
 public void onCreate() {
 super.onCreate();
 mNotificationManager = (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
 
 }
 
 @Override
 public int onStartCommand(Intent intent, int flags, int startId) {
 if (intent == null) {
  notifyMsg("温馨提醒", "文件下载失败", 0);
  stopSelf();
 }
 mDownloadUrl = intent.getStringExtra("apkUrl");//获取下载APK的链接
 downloadFile(mDownloadUrl);//下载APK
 return super.onStartCommand(intent, flags, startId);
 }
 
 @Nullable
 @Override
 public IBinder onBind(Intent intent) {
 return null;
 }
 
 private void notifyMsg(String title, String content, int progress) {
 
 NotificationCompat.Builder builder = new NotificationCompat.Builder(this);//为了向下兼容,这里采用了v7包下的NotificationCompat来构造
 builder.setSmallIcon(R.mipmap.icon_login_logo).setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.icon_login_logo)).setContentTitle(title);
 if (progress > 0 && progress < 100) {
  //下载进行中
  builder.setProgress(100, progress, false);
 } else {
  builder.setProgress(0, 0, false);
 }
 builder.setAutoCancel(true);
 builder.setWhen(System.currentTimeMillis());
 builder.setContentText(content);
 if (progress >= 100) {
  //下载完成
  builder.setContentIntent(getInstallIntent());
 }
 mNotification = builder.build();
 mNotificationManager.notify(0, mNotification);
 
 
 }
 
 /**
 * 安装apk文件
 *
 * @return
 */
 private PendingIntent getInstallIntent() {
 File file = new File(StorageUtil.DOWNLOAD_DIR + "APP文件名");
 Intent intent = new Intent(Intent.ACTION_VIEW);
 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 intent.setDataAndType(Uri.parse("file://" + file.getAbsolutePath()), "application/vnd.android.package-archive");
 PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
 return pendingIntent;
 }
 
 
 /**
 * 下载apk文件
 *
 * @param url
 */
 private void downloadFile(String url) {
 
 OkHttpUtils.get().url(url).build().execute(new FileCallBack(StorageUtil.DOWNLOAD_DIR, "APP文件名") {
  @Override
  public void onError(Call call, Exception e, int id) {
  notifyMsg("温馨提醒", "文件下载失败", 0);
  stopSelf();
  }
 
  @Override
  public void onResponse(File response, int id) {
  //当文件下载完成后回调
  notifyMsg("温馨提醒", "文件下载已完成", 100);
  stopSelf();
 
 
  }
 
  @Override
  public void inProgress(float progress, long total, int id) {
  //progress*100为当前文件下载进度,total为文件大小
  if ((int) (progress * 100) % 10 == 0) {
   //避免频繁刷新View,这里设置每下载10%提醒更新一次进度
   notifyMsg("温馨提醒", "文件正在下载..", (int) (progress * 100));
  }
  }
 });
 }
}

然后我们只需要在我们想要的更新APP的时候去调起这个服务即可,比如在系统设置里的"版本检查"等

?
Intent intent = new Intent(mContext, DownloadService.class);
intent.putExtra("apkUrl", "APK下载地址");
startService(intent);

总结

这里我只是粗略演示本地自动更新APP的功能,在实际应用中,我们应该配合服务端来做,比如在用户启动APP的时候去比对版本号,如果版本号低于服务器的版本号,那么此时服务端应该给客户端一个透传推送,这里的推送内容应该为新版本APP的下载地址,此时就可以根据该地址来下载新版APP了,当遇到重大更新,不再对老版本进行兼容的时候,可以强制用户升级,这里的方案有很多,比如调用系统级对话框,让用户没办法取消等操作,这里就不做更多描述。以上就是这篇文章的全部内容,希望对有需要的人能有所帮助。



框架内部支持中/英文(其他语言只需要在对应的string.xml中取相同的名字即可)内部对话框背景图片、按钮支持自定义了查看版本中的Log只需要过滤AppUpdate开头的Tag重点: 如果没有设置downloadPath则默认为getExternalCacheDir()目录,同时不会申请[存储]权限!目录编译问题效果图功能介绍DownloadManagerUpdateConfiguration使用步骤Demo下载体验版本更新记录结语编译问题因为适配了Android O的通知栏,所以依赖的v7包版本比较高appcompat-v7:26.1.0使用的gradle版本为gradle-4.1-all,所以建议使用Android Studio 3.0及以上的版本打开此项目效果图     功能介绍 支持断点下载 支持后台下载 支持自定义下载过程 支持 设备 >= Android M 动态权限的申请 支持通知栏进度条展示(或者自定义显示进度) 支持Android N 支持Android O 支持中/英文双语 支持自定内置对话框的样式 使用HttpURLConnection下载,未集成其他第三方框架更加详细的文档参阅此处《AppUpdate API文档》DownloadManager:配置文档初始化使用DownloadManager.getInstance(this)属性描述默认值是否必须设置context上下文nulltrueapkUrlapk的下载地址nulltrueapkNameapk下载好的名字nulltruedownloadPathapk下载的位置getExternalCacheDir()falseshowNewerToast是否提示用户 "当前已是最新版本"falsefalsesmallIcon通知栏的图标(资源id)-1trueconfiguration这个库的额外配置nullfalseapkVersionCode更新apk的versionCode (如果设置了那么库中将会进行版本判断下面的属性也就需要设置了)1falseapkVersionName更新apk的versionNamenullfalseapkDescription更新描述nullfalseapkSize新版本的安装包大小(单位M)nullfalseauthorities兼容Android N uri授权应用包名falseUpdateConfiguration:配置文档属性描述默认值notifyId通知栏消息id1011notificationChannel适配Android O的渠道通知详情查阅源码httpManager设置自己的下载过程nullbreakpointDownload是否需要支持断点下载trueenableLog是否需要日志输出trueonDownloadListener下载过程的回调nulljumpInstallPage下载完成是否自动弹出安装页面trueshowNotification是否显示通知栏进度(后台下载提示)trueforcedUpgrade是否强制升级falseonButtonClickListener按钮点击事件回调nulldialogImage对话框背景图片资源(图片规范参考demo)-1dialogButtonColor对话框按钮的颜色-1dialogButtonTextColor对话框按钮的文字颜色-1所有版本:点击查看使用步骤第一步: app/build.gradle进行依赖implementation 'com.azhon:appupdate:1.7.3'第二步:创建DownloadManager,更多用法请查看这里示例代码DownloadManager manager = DownloadManager.getInstance(this); manager.setApkName("appupdate.apk")         .setApkUrl("https://raw.githubusercontent.com/azhon/AppUpdate/master/apk/appupdate.apk")         .setSmallIcon(R.mipmap.ic_launcher)         //可设置,可不设置         .setConfiguration(configuration)         .download();第三步:兼容Android N 及以上版本,在你应用的Manifest.xml添加如下代码<--! android:authorities="${applicationId}"  这个值必须与DownloadManager中的authorities一致(不设置则为应用包名)--> <provider     android:name="android.support.v4.content.FileProvider"     android:authorities="${applicationId}"     android:exported="false"     android:grantUriPermissions="true">     <meta-data         android:name="android.support.FILE_PROVIDER_PATHS"         android:resource="@xml/file_paths_public" /> </provider>第四步:资源文件res/xml/file_paths_public.xml内容<?xml version="1.0" encoding="utf-8"?> <paths>     <external-path         name="app_update_external"         path="/" />     <external-cache-path         name="app_update_cache"         path="/" /> </paths>兼容Android O及以上版本,需要设置NotificationChannel(通知渠道);库中已经写好可以前往查阅NotificationUtil.java温馨提示:升级对话框中的内容是可以上下滑动的哦!如果需要实现自己一套下载过程,只需要继承BaseHttpDownloadManager 并使用listener更新进度public class MyDownload extends BaseHttpDownloadManager {}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值