热门标签 | HotTags
当前位置:  开发笔记 > 运维 > 正文

android实现通知栏下载更新app示例

这篇文章主要介绍了android实现通知栏下载更新app示例,需要的朋友可以参考下

1.设计思路,使用VersionCode定义为版本升级参数。
android为我们定义版本提供了2个属性:

代码如下:

android:versiOnCode="1"
android:versiOnName="1.0"
>


谷歌建议我们使用versionCode自增来表明版本升级,无论是大的改动还是小的改动,而versionName是显示用户看的软件版本,作为显示使用。所以我们选择了VersionCode作为我们定义版本升级的参数。

2.工程目录
为了对真实项目或者企业运用有实战指导作用,我模拟一个独立的项目,工程目录设置的合理严谨一些,而不是仅仅一个demo。
假设我们以上海地铁为项目,命名为"Subway",工程结构如下,

3.版本初始化和版本号的对比。
首先定义在全局文件Global.java中定义变量localVersion和serverVersion分别存放本地版本号和服务器版本号。

代码如下:

public class Global {
//版本信息
public static int localVersion = 0;
public static int serverVersion = 0;
public static String downloadDir = "app/download/";
}

因为本文只是重点说明升级更新,为了防止其他太多无关代码冗余其中,我直接在SubwayApplication中定义方法initGlobal()方法。
代码如下:

/**
* 初始化全局变量
* 实际工作中这个方法中serverVersion从服务器端获取,最好在启动画面的activity中执行
*/
public void initGlobal(){
try{
Global.localVersion = getPackageManager().getPackageInfo(getPackageName(),0).versionCode; //设置本地版本号
Global.serverVersion = 1;//假定服务器版本为2,本地版本默认是1
}catch (Exception ex){
ex.printStackTrace();
}
}

如果检测到新版本发布,提示用户是否更新,我在SubwayActivity中定义了checkVersion()方法:
代码如下:

/**
* 检查更新版本
*/
public void checkVersion(){

if(Global.localVersion //发现新版本,提示用户更新
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(SubwayActivity.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(),文章后面我会附上代码
}
}

好,我们现在把这些东西串一下:
第一步在SubwayApplication的onCreate()方法中执行initGlobal()初始化版本变量。

代码如下:

public void onCreate() {
super.onCreate();
initGlobal();
}

第二步在SubwayActivity的onCreate()方法中检测版本更新checkVersion()。
代码如下:

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
checkVersion();

现在入口已经打开,在checkVersion方法的第18行代码中看出,当用户点击更新,我们开启更新服务,从服务器上下载最新版本。
4.使用Service在后台从服务器端下载,完成后提示用户下载完成,并关闭服务。
定义一个服务UpdateService.java,首先定义与下载和通知相关的变量:

代码如下:

//标题
private int titleId = 0;

//文件存储
private File updateDir = null;  
private File updateFile = null;

//通知栏
private NotificationManager updateNotificatiOnManager= null;
private Notification updateNotification = null;
//通知栏跳转Intent
private Intent updateIntent = null;
private PendingIntent updatePendingIntent = null;

在onStartCommand()方法中准备相关的下载工作:

代码如下:

@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(),Global.downloadDir);
updateFile = new File(updateDir.getPath(),getResources().getString(titleId)+".apk");
}

this.updateNotificatiOnManager= (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
this.updateNotification = new Notification();

//设置下载过程中,点击通知栏,回到主界面
updateIntent = new Intent(this, SubwayActivity.class);
updatePendingIntent = PendingIntent.getActivity(this,0,updateIntent,0);
//设置通知栏显示内容
updateNotification.icon = R.drawable.arrow_down_float;
updateNotification.tickerText = "开始下载";
updateNotification.setLatestEventInfo(this,"上海地铁","0%",updatePendingIntent);
//发出通知
updateNotificationManager.notify(0,updateNotification);

//开启一个新的线程下载,如果使用Service同步下载,会导致ANR问题,Service本身也会阻塞
new Thread(new updateRunnable()).start();//这个是下载的重点,是下载的过程

return super.onStartCommand(intent, flags, startId);
}


上面都是准备工作

从代码中可以看出来,updateRunnable类才是真正下载的类,出于用户体验的考虑,这个类是我们单独一个线程后台去执行的。
下载的过程有两个工作:1.从服务器上下载数据;2.通知用户下载的进度。
线程通知,我们先定义一个空的updateHandler。
[/code]
private Handler updateHandler = new Handler(){
@Override
public void handleMessage(Message msg) {

}
};
[/code]
再来创建updateRunnable类的真正实现:

代码如下:

class updateRunnable implements Runnable {
Message message = updateHandler.obtainMessage();
public void run() {
message.what = DOWNLOAD_COMPLETE;
try{
//增加权限;
if(!updateDir.exists()){
updateDir.mkdirs();
}
if(!updateFile.exists()){
updateFile.createNewFile();
}
//下载函数,以QQ为例子
//增加权限;
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);
}
}
}


下载函数的实现有很多,我这里把代码贴出来,而且我们要在下载的时候通知用户下载进度:
代码如下:

public long downloadUpdateFile(String downloadUrl, File saveFile) throws Exception {
//这样的下载代码很多,我就不做过多的说明
int downloadCount = 0;
int currentSize = 0;
long totalSize = 0;
int updateTotalSize = 0;

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);
updateNotificationManager.notify(0, updateNotification);
}
}
} finally {
if(httpConnection != null) {
httpConnection.disconnect();
}
if(is != null) {
is.close();
}
if(fos != null) {
fos.close();
}
}
return totalSize;
}

下载完成后,我们提示用户下载完成,并且可以点击安装,那么我们来补全前面的Handler吧。
先在UpdateService.java定义2个常量来表示下载状态:

代码如下:

//下载状态
private final static int DOWNLOAD_COMPLETE = 0;
private final static int DOWNLOAD_FAIL = 1;

根据下载状态处理主线程:
代码如下:

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, "上海地铁", "下载完成,点击安装。", updatePendingIntent);
updateNotificationManager.notify(0, updateNotification);

//停止服务
stopService(updateIntent);
case DOWNLOAD_FAIL:
//下载失败
updateNotification.setLatestEventInfo(UpdateService.this, "上海地铁", "下载完成,点击安装。", updatePendingIntent);
updateNotificationManager.notify(0, updateNotification);
default:
stopService(updateIntent);
}
}
};



至此,文件下载并且在通知栏通知进度。
发现本人废话很多,其实几句话的事情,来来回回写了这么多,啰嗦了,后面博文我会朝着精简方面努力。
PS:前面说要附上cheanUpdateFile()的代码
代码如下:

File updateFile = new File(Global.downloadDir,getResources().getString(R.string.app_name)+".apk");
if(updateFile.exists()){
//当不需要的时候,清除之前的下载文件,避免浪费用户空间
updateFile.delete();
}


推荐阅读
  • 本文详细介绍如何使用arm-eabi-gdb调试Android平台上的C/C++程序。通过具体步骤和实用技巧,帮助开发者更高效地进行调试工作。 ... [详细]
  • 深入理解Cookie与Session会话管理
    本文详细介绍了如何通过HTTP响应和请求处理浏览器的Cookie信息,以及如何创建、设置和管理Cookie。同时探讨了会话跟踪技术中的Session机制,解释其原理及应用场景。 ... [详细]
  • UNP 第9章:主机名与地址转换
    本章探讨了用于在主机名和数值地址之间进行转换的函数,如gethostbyname和gethostbyaddr。此外,还介绍了getservbyname和getservbyport函数,用于在服务器名和端口号之间进行转换。 ... [详细]
  • 360SRC安全应急响应:从漏洞提交到修复的全过程
    本文详细介绍了360SRC平台处理一起关键安全事件的过程,涵盖从漏洞提交、验证、排查到最终修复的各个环节。通过这一案例,展示了360在安全应急响应方面的专业能力和严谨态度。 ... [详细]
  • 本文详细分析了Hive在启动过程中遇到的权限拒绝错误,并提供了多种解决方案,包括调整文件权限、用户组设置以及环境变量配置等。 ... [详细]
  • 使用Python在SAE上开发新浪微博应用的初步探索
    最近重新审视了新浪云平台(SAE)提供的服务,发现其已支持Python开发。本文将详细介绍如何利用Django框架构建一个简单的新浪微博应用,并分享开发过程中的关键步骤。 ... [详细]
  • Android 九宫格布局详解及实现:人人网应用示例
    本文深入探讨了人人网Android应用中独特的九宫格布局设计,解析其背后的GridView实现原理,并提供详细的代码示例。这种布局方式不仅美观大方,而且在现代Android应用中较为少见,值得开发者借鉴。 ... [详细]
  • XNA 3.0 游戏编程:从 XML 文件加载数据
    本文介绍如何在 XNA 3.0 游戏项目中从 XML 文件加载数据。我们将探讨如何将 XML 数据序列化为二进制文件,并通过内容管道加载到游戏中。此外,还会涉及自定义类型读取器和写入器的实现。 ... [详细]
  • 本文深入探讨了Linux系统中网卡绑定(bonding)的七种工作模式。网卡绑定技术通过将多个物理网卡组合成一个逻辑网卡,实现网络冗余、带宽聚合和负载均衡,在生产环境中广泛应用。文章详细介绍了每种模式的特点、适用场景及配置方法。 ... [详细]
  • 本文探讨了在不使用服务器控件的情况下,如何通过多种方法获取并修改页面中的HTML元素值。除了常见的AJAX方式,还介绍了其他可行的技术方案。 ... [详细]
  • 解读MySQL查询执行计划的详细指南
    本文旨在帮助开发者和数据库管理员深入了解如何解读MySQL查询执行计划。通过详细的解析,您将掌握优化查询性能的关键技巧,了解各种访问类型和额外信息的含义。 ... [详细]
  • 掌握远程执行Linux脚本和命令的技巧
    本文将详细介绍如何利用Python的Paramiko库实现远程执行Linux脚本和命令,帮助读者快速掌握这一实用技能。通过具体的示例和详尽的解释,让初学者也能轻松上手。 ... [详细]
  • 本文探讨了如何优化和正确配置Kafka Streams应用程序以确保准确的状态存储查询。通过调整配置参数和代码逻辑,可以有效解决数据不一致的问题。 ... [详细]
  • 解决MongoDB Compass远程连接问题
    本文记录了在使用阿里云服务器部署MongoDB后,通过MongoDB Compass进行远程连接时遇到的问题及解决方案。详细介绍了从防火墙配置到安全组设置的各个步骤,帮助读者顺利解决问题。 ... [详细]
  • 本文详细介绍了如何使用ActionScript 3.0 (AS3) 连接并操作MySQL数据库。通过具体的代码示例和步骤说明,帮助开发者理解并实现这一过程。 ... [详细]
author-avatar
西南科技大学地质协会_927
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有