对于安卓用户来说,手机应用市场说满天飞可是一点都不夸张,比如小米,魅族,百度,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的下载

  1. import android.app.Notification;
  2. import android.app.notificationmanager;
  3. import android.app.PendingIntent;
  4. import android.app.Service;
  5. import android.content.Intent;
  6. import android.graphics.BitmapFactory;
  7. import android.net.Uri;
  8. import android.os.IBinder;
  9. import android.support.annotation.Nullable;
  10. import android.support.v7.app.NotificationCompat;
  11. import com.fangku.commonlibrary.utils.StorageUtil;
  12. import com.zhy.http.okhttp.OkHttpUtils;
  13. import com.zhy.http.okhttp.callback.FileCallBack;
  14. import java.io.File;
  15. import okhttp3.Call;
  16. /**
  17. * 自动下载更新apk服务
  18. * Create by: chenwei.li
  19. * Date: 2016-08-14
  20. * time: 09:50
  21. * Email: lichenwei.me@foxmail.com
  22. */
  23. public class DownloadService extends Service {
  24. private String mDownloadUrl;//APK的下载路径
  25. private notificationmanager mnotificationmanager;
  26. private Notification mNotification;
  27. @Override
  28. public void onCreate() {
  29. super.onCreate();
  30. mnotificationmanager = (notificationmanager) getSystemService(Service.NOTIFICATION_SERVICE);
  31. }
  32. @Override
  33. public int onStartCommand(Intent intent,int flags,int startId) {
  34. if (intent == null) {
  35. notifyMsg("温馨提醒","文件下载失败",0);
  36. stopSelf();
  37. }
  38. mDownloadUrl = intent.getStringExtra("apkUrl");//获取下载APK的链接
  39. downloadFile(mDownloadUrl);//下载APK
  40. return super.onStartCommand(intent,flags,startId);
  41. }
  42. @Nullable
  43. @Override
  44. public IBinder onBind(Intent intent) {
  45. return null;
  46. }
  47. private void notifyMsg(String title,String content,int progress) {
  48. NotificationCompat.Builder builder = new NotificationCompat.Builder(this);//为了向下兼容,这里采用了v7包下的NotificationCompat来构造
  49. builder.setSmallIcon(R.mipmap.icon_login_logo).setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.icon_login_logo)).setContentTitle(title);
  50. if (progress > 0 && progress < 100) {
  51. //下载进行中
  52. builder.setProgress(100,progress,false);
  53. } else {
  54. builder.setProgress(0,false);
  55. }
  56. builder.setAutoCancel(true);
  57. builder.setWhen(System.currentTimeMillis());
  58. builder.setContentText(content);
  59. if (progress >= 100) {
  60. //下载完成
  61. builder.setContentIntent(getInstallIntent());
  62. }
  63. mNotification = builder.build();
  64. mnotificationmanager.notify(0,mNotification);
  65. }
  66. /**
  67. * 安装apk文件
  68. *
  69. * @return
  70. */
  71. private PendingIntent getInstallIntent() {
  72. File file = new File(StorageUtil.DOWNLOAD_DIR + "APP文件名");
  73. Intent intent = new Intent(Intent.ACTION_VIEW);
  74. intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  75. intent.setDataAndType(Uri.parse("file://" + file.getAbsolutePath()),"application/vnd.android.package-archive");
  76. PendingIntent pendingIntent = PendingIntent.getActivity(this,intent,PendingIntent.FLAG_UPDATE_CURRENT);
  77. return pendingIntent;
  78. }
  79. /**
  80. * 下载apk文件
  81. *
  82. * @param url
  83. */
  84. private void downloadFile(String url) {
  85. OkHttpUtils.get().url(url).build().execute(new FileCallBack(StorageUtil.DOWNLOAD_DIR,"APP文件名") {
  86. @Override
  87. public void onError(Call call,Exception e,int id) {
  88. notifyMsg("温馨提醒",0);
  89. stopSelf();
  90. }
  91. @Override
  92. public void onResponse(File response,int id) {
  93. //当文件下载完成后回调
  94. notifyMsg("温馨提醒","文件下载已完成",100);
  95. stopSelf();
  96. }
  97. @Override
  98. public void inProgress(float progress,long total,int id) {
  99. //progress*100为当前文件下载进度,total为文件大小
  100. if ((int) (progress * 100) % 10 == 0) {
  101. //避免频繁刷新View,这里设置每下载10%提醒更新一次进度
  102. notifyMsg("温馨提醒","文件正在下载..",(int) (progress * 100));
  103. }
  104. }
  105. });
  106. }
  107. }

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

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

总结

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

最新文章

  1. 【url重写】
  2. CSV文件的规范
  3. kali linux安装virtualbox虚拟机之爬坑经历
  4. Windows7下安装搭建Ngnix教程和配置详解
  5. JS中的!=、== 、!==、===的用法和区别。
  6. hdu 3357 水题
  7. Java基础知识强化92:日期工具类的编写和测试案例
  8. MySQL JDBC事务处理、封装JDBC工具类
  9. linux虚拟机安装演示
  10. 【面试问题】——秋招面试中遇到的一些问题&amp;思维导图&amp;反思
  11. PHPUnit-附录 C. XML 配置文件
  12. Java基础:Java虚拟机(JVM)
  13. Solidity属性和方法的访问权限
  14. 在同一台电脑部署多个Tomcat服务
  15. spec 文件详解
  16. k8s中新建一个namespace和harborsecret的yaml文件
  17. java struts2入门学习--基于xml文件的声明式验证
  18. 对innodb_flush_log_at_commit参数的写日志和刷盘行为进行图解
  19. php array_map array_filter sort
  20. fireDAC oracle

热门文章

  1. 学习Java Day15
  2. require.context 自动引入指定目录下的文件、组件、reducer
  3. odoo 为可编辑列表视图字段搜索添加查询过滤条件
  4. navicat无法连接linux内的防火墙
  5. ctf命令执行刷题
  6. nodejs npm错误Error:UNKNOWN:unknown error,mkdir &#39;D:\Develop\nodejs\node_global&#39;at Error(可行)
  7. CSS3移动动画
  8. Linux 一次性创建多个文件
  9. 【MySQL速通篇001】5000字吃透MySQL部分重要知识点
  10. api规范PHP,RESTful API规范(详细版)