Android实现APP自动更新
当有更新时,会弹出一个提示框,点击确定,则在通知栏创建一个进度条进行下载,点击取消,则取消更新。
1.创建布局文件notification_item.xml,用于在通知栏生成一个进度条和下载图标。
<?xml version="1.0" encoding="utf-8"?>
<relativelayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="3dp">
<imageview
android:id="@+id/notificationImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@android:drawable/stat_sys_download">
<textview
android:id="@+id/notificationTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignparentright="true"
android:layout_torightof="@id/notificationImage"
android:paddingleft="6dp"
android:textcolor="#FF000000">
<textview
android:id="@+id/notificationPercent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/notificationImage"
android:paddingtop="2dp"
android:textcolor="#FF000000">
<progressbar
android:id="@+id/notificationProgress"
style="@style/ProgressBarHorizontal_color"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignleft="@id/notificationTitle"
android:layout_alignparentright="true"
android:layout_aligntop="@id/notificationPercent"
android:layout_below="@id/notificationTitle"
android:paddingleft="6dp"
android:paddingright="3dp"
android:paddingtop="2dp"></progressbar>
</textview>
</textview>
</imageview>
</relativelayout>
2.创建AppContext类,该类继承自Application。
import android.app.Application;
import android.content.Context;
import com.test.update.config.Config;
public class AppContext extends Application {
private static AppContext appInstance;
private Context context;
public static AppContext getInstance() {
return appInstance;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
appInstance = this;
context = this.getBaseContext();
// // 获取当前版本号
// try {
// PackageInfo packageInfo = getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
// Config.localVersion = packageInfo.versionCode;
// Config.serverVersion = 1;// 假定服务器版本为2,本地版本默认是1
// } catch (NameNotFoundException e) {
// e.printStackTrace();
// }
initGlobal();
}
public void initGlobal() {
try {
Config.localVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode; // 设置本地版本号
Config.serverVersion = 2;// 假定服务器版本为2,本地版本默认是1--实际开发中是从服务器获取最新版本号,android具体与后端的交互见我另///外的博文
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
3.创建配置文件类Config.java,在这个类里面定义一些与版本相关的常量
public class Config { //版本信息 public static int localVersion = 0; public static int serverVersion = 0; /* 下载包安装路径 */ public static final String savePath = /sdcard/test/; public static final String saveFileName = savePath + test.apk; }
4.编写更新服务类UpdateServcie.java
import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import android.annotation.SuppressLint; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.net.Uri; import android.os.Environment; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.widget.RemoteViews; import com.test.update.config.Config; public class UpdateService extends Service { // 标题 private int titleId = 0; // 文件存储 private File updateDir = null; private File updateFile = null; // 下载状态 private final static int DOWNLOAD_COMPLETE = 0; private final static int DOWNLOAD_FAIL = 1; // 通知栏 private NotificationManager updateNotificationManager = null; private Notification updateNotification = null; // 通知栏跳转Intent private Intent updateIntent = null; private PendingIntent updatePendingIntent = null; /*** * 创建通知栏 */ RemoteViews contentView; // 这样的下载代码很多,我就不做过多的说明 int downloadCount = 0; int currentSize = 0; long totalSize = 0; int updateTotalSize = 0; // 在onStartCommand()方法中准备相关的下载工作: @SuppressWarnings(deprecation) @Override public int onStartCommand(Intent intent, int flags, int startId) { // 获取传值 titleId = intent.getIntExtra(titleId, 0); // 创建文件 if (android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment.getExternalStorageState())) { updateDir = new File(Environment.getExternalStorageDirectory(), Config.saveFileName); updateFile = new File(updateDir.getPath(), getResources().getString(titleId) + .apk); } this.updateNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); this.updateNotification = new Notification(); // 设置下载过程中,点击通知栏,回到主界面 updateIntent = new Intent(this, UpdateActivity.class); updatePendingIntent = PendingIntent.getActivity(this, 0, updateIntent, 0); // 设置通知栏显示内容 updateNotification.icon = R.drawable.ic_launcher; updateNotification.tickerText = 开始下载; updateNotification.setLatestEventInfo(this, QQ, 0%, updatePendingIntent); // 发出通知 updateNotificationManager.notify(0, updateNotification); // 开启一个新的线程下载,如果使用Service同步下载,会导致ANR问题,Service本身也会阻塞 new Thread(new updateRunnable()).start();// 这个是下载的重点,是下载的过程 return super.onStartCommand(intent, flags, startId); } @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return null; } @SuppressLint(HandlerLeak) private Handler updateHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case DOWNLOAD_COMPLETE: // 点击安装PendingIntent Uri uri = Uri.fromFile(updateFile); Intent installIntent = new Intent(Intent.ACTION_VIEW); installIntent.setDataAndType(uri, application/vnd.android.package-archive); updatePendingIntent = PendingIntent.getActivity(UpdateService.this, 0, installIntent, 0); updateNotification.defaults = Notification.DEFAULT_SOUND;// 铃声提醒 updateNotification.setLatestEventInfo(UpdateService.this, QQ, 下载完成,点击安装。, updatePendingIntent); updateNotificationManager.notify(0, updateNotification); // 停止服务 stopService(updateIntent); case DOWNLOAD_FAIL: // 下载失败 updateNotification.setLatestEventInfo(UpdateService.this, QQ, 下载完成,点击安装。, updatePendingIntent); updateNotificationManager.notify(0, updateNotification); default: stopService(updateIntent); } } }; public long downloadUpdateFile(String downloadUrl, File saveFile) throws Exception { HttpURLConnection httpConnection = null; InputStream is = null; FileOutputStream fos = null; try { URL url = new URL(downloadUrl); httpConnection = (HttpURLConnection) url.openConnection(); httpConnection.setRequestProperty(User-Agent, PacificHttpClient); if (currentSize > 0) { httpConnection.setRequestProperty(RANGE, bytes= + currentSize + -); } httpConnection.setConnectTimeout(10000); httpConnection.setReadTimeout(20000); updateTotalSize = httpConnection.getContentLength(); if (httpConnection.getResponseCode() == 404) { throw new Exception(fail!); } is = httpConnection.getInputStream(); fos = new FileOutputStream(saveFile, false); byte buffer[] = new byte[4096]; int readsize = 0; while ((readsize = is.read(buffer)) > 0) { fos.write(buffer, 0, readsize); totalSize += readsize; // 为了防止频繁的通知导致应用吃紧,百分比增加10才通知一次 if ((downloadCount == 0) || (int) (totalSize * 100 / updateTotalSize) - 10 > downloadCount) { downloadCount += 10; updateNotification.setLatestEventInfo(UpdateService.this, 正在下载, (int) totalSize * 100 / updateTotalSize + %, updatePendingIntent); /*** * 在这里我们用自定的view来显示Notification */ updateNotification.contentView = new RemoteViews(getPackageName(), R.layout.notification_item); updateNotification.contentView.setTextViewText(R.id.notificationTitle, 正在下载); updateNotification.contentView.setProgressBar(R.id.notificationProgress, 100, downloadCount, false); updateNotificationManager.notify(0, updateNotification); } } } finally { if (httpConnection != null) { httpConnection.disconnect(); } if (is != null) { is.close(); } if (fos != null) { fos.close(); } } return totalSize; } class updateRunnable implements Runnable { Message message = updateHandler.obtainMessage(); public void run() { message.what = DOWNLOAD_COMPLETE; try { // 增加权限<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">; if (!updateDir.exists()) { updateDir.mkdirs(); } if (!updateFile.exists()) { updateFile.createNewFile(); } // 下载函数,以QQ为例子 // 增加权限<uses-permission android:name="android.permission.INTERNET">; long downloadSize = downloadUpdateFile(http://softfile.3g.qq.com:8080/msoft/179/1105/10753/MobileQQ1.0(Android)_Build0198.apk, updateFile); if (downloadSize > 0) { // 下载成功 updateHandler.sendMessage(message); } } catch (Exception ex) { ex.printStackTrace(); message.what = DOWNLOAD_FAIL; // 下载失败 updateHandler.sendMessage(message); } } } }
5.编写活动类UpdateActivity
import com.test.update.config.Config; import android.support.v4.app.Fragment; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; public class UpdateActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); checkVersion(); } /** * 检查更新版本 */ public void checkVersion() { if (Config.localVersion < Config.serverVersion) { Log.i(hgncxzy, ==============================); // 发现新版本,提示用户更新 AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle(软件升级) .setMessage(发现新版本,建议立即更新使用.) .setPositiveButton(更新, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // 开启更新服务UpdateService // 这里为了把update更好模块化,可以传一些updateService依赖的值 // 如布局ID,资源ID,动态获取的标题,这里以app_name为例 Intent updateIntent = new Intent(UpdateActivity.this, UpdateService.class); updateIntent.putExtra(titleId, R.string.app_name); startService(updateIntent); } }) .setNegativeButton(取消, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); alert.create().show(); } else { // 清理工作,略去 // cheanUpdateFile() } } }
6.在配置文件中添加权限以及将服务静态加载(。
Android实现APP自动更新相关推荐
- 【安卓开发 】Android初级开发(十)Android中app自动更新版本号比较
//版本号比较:前者小返回true,前者大返回false public static boolean versionCompareTo(String version1, String version2 ...
- Android App自动更新解决方案(DownloadManager)
Android App自动更新解决方案(DownloadManager) 参考文章: (1)Android App自动更新解决方案(DownloadManager) (2)https://www.cn ...
- android通知栏应用程序更新,Android App自动更新之通知栏下载
本文实例为大家分享了Android App自动更新通知栏下载的具体代码,供大家参考,具体内容如下 版本更新说明 这里有调用UpdateService启动服务检查下载安装包等 1. 文件下载,下完后写入 ...
- Android如何实现APP自动更新
先来看看要实现的效果图: 对于安卓用户来说,手机应用市场说满天飞可是一点都不夸张,比如小米,魅族,百度,360,机锋,应用宝等等,当我们想上线一款新版本APP时,先不说渠道打包的麻烦,单纯指上传APP ...
- Android APP 自动更新实现(适用Android9.0)
Android App自动更新基本上是每个App都需具备的功能,参考网上各种资料,自己整理了下,先来看看大致的界面: 一.实现思路: 1.发布Android App时,都会生成output-metad ...
- web app升级—带进度条的App自动更新
带进度条的App自动更新,效果如下图所示: 技术:vue.vant-ui.5+ 封装独立组件AppProgress.vue: <template><div><van- ...
- 安卓APP自动更新实现
一.参考文献 简单实现安卓app自动更新功能 - 简书 安卓app自动更新功能完美实现_白云天的博客-CSDN博客_android 自动更新 Android 实现自动更新及强制更新功能_farley的 ...
- flutter APP自动更新
flutter APP自动更新 前言 在pubspec.yaml中安装依赖 在main.dart文件中,初始化FlutterDownLoader 配置网络 在AndroidManifest.xml新增 ...
- 安卓APP自动更新功能实现
安卓APP自动更新功能实现 前言 代码实现 前言 安卓App自动更新基本上是每个App都需要具备的功能,接下来介绍一下实现自动更新的步骤. 代码实现 App自动更新主要分为新版本检测.升级弹窗.下载升 ...
最新文章
- mysql nextval同步锁_mysql中实现类似oracle中的nextval函数
- Struts2学习笔记-part1: 快速起步
- 21天精通python-21天学通Python 完整pdf扫描版[58MB]
- c++深拷贝和浅拷贝的区别?
- 数据挖掘:数据仓库相关知识笔记
- 作业 给计算机编号 winform
- 一程序员反应职场怪现象
- 一些关于直播间人货场的打造干货,直播电商新手必须要了解人货场的概念
- python变量命名规则思维导图_python基础知识点思维导图
- 侧信道实验实验三 S盒CPA侧信道攻击
- Python 结构体数组初始化代码示例
- JefferyZhao教导我们...
- 谷歌浏览器 Chrome 安装 Tampermonkey 油猴插件的方法
- 通过youtube上传视频赚钱并免费宣传你的业务
- java批量发短信软件_如何获得批量短信的发送短信
- java:数组的静态和动态声明
- Js 显示 服务器 目录,js获得服务器目录
- 大学物理稳恒电场——恒定电流
- 精通脚本黑客--电骡下载
- 分子对接软件(薛定谔Schrodinger) 使用
热门文章
- springboot 加入mysql_Spring Boot 添加MySQL数据库及JPA实例
- 5步教你完成linux 配置中文输入法(以搜狗为例)
- Opencv学习笔记 图像拼接一全景拼接
- python k-近邻算法 案例实战 预测Pima 印度安人的糖尿病
- mysql phpmyadmin 文件夹_PHPMyadmin 配置文件详解(配置)
- [游戏模版3] Win32 画笔 画刷 图形
- C语言之牛客网初级入门编程
- R语言如何实现主成分分析(PCA),最全详细教材
- 如何在个人电脑上创建mysql
- 用易看小说cms搭建自己的小说站