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 < Global.serverVersion){

//发现新版本,提示用户更新

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();

}

android通知栏自定义软件,android实现通知栏下载更新app示例相关推荐

  1. android如何自定义dialog,Android—自定义Dialog

    在 Android 日常的开发中,Dialog 使用是比较广泛的.无论是提示一个提示语,还是确认信息,还是有一定交互的(弹出验证码,输入账号密码登录等等)对话框. 而我们去看一下原生的对话框,虽然随着 ...

  2. android通知栏自定义软件,免root状态栏美化神器

    免root状态栏美化神器小编特意为广大小伙伴带来的可直接修改状态栏颜色的工具,用户还可以自定义运行商,状态栏美化神器!感兴趣的用户赶快前来西西软件园下载体验吧! 免root状态栏美化神器使用介绍 我们 ...

  3. android照片编辑软件,照片编辑免费软件下载-照片编辑软件app下载 v7.45最新版_5577安卓网...

    照片编辑免费软件app下载,提供给你全新的图片处理工具,这是软件包含了丰富的功能内容,软件一键即可轻松对各种照片組合.编辑和拼貼,那么有需要图片处理的用户下载该app使用吧! [软件特色] [ 拼图编 ...

  4. android如何自定义viewpager,Android自定义ViewPager实现个性化的图片切换效果

    第一次见到ViewPager这个控件,瞬间爱不释手,做东西的主界面通通ViewPager,以及图片切换也抛弃了ImageSwitch之类的,开始让ViewPager来做.时间长了,ViewPager的 ...

  5. android开发自定义键盘,Android 总结:自定义键盘实现原理和三种实例详解

    1.实现原理 实现软键盘主要用到了系统的两个类 Keyboard 和 KeyboardView .html 1. Keyboard 用于监听虚拟键盘:java Loads an XML descrip ...

  6. android toast 自定义时间,Android Toast自定义显示时间

    Toast是Android中使用频率较高的弹窗提示手段,使用起来简单.方便.常规使用方法这里不做说明,继前一篇博客<Android中Toast全屏显示> ,其中抛砖引玉的给出一个简单的实现 ...

  7. android sqlite自定义函数,Android中自定义一个View的方法详解

    本文实例讲述了Android中自定义一个View的方法.分享给大家供大家参考,具体如下: Android中自定义View的实现比较简单,无非就是继承父类,然后重载方法,即便如此,在实际编码中难免会遇到 ...

  8. android 第三方加密软件,Android实用图文教程之代码混淆、第三方平台加固加密、渠道分发...

    第一步:代码混淆(注意引入的第三方jar) 在新版本的ADT创建项目时,混码的文件不再是proguard.cfg,而是project.properties和proguard-project.txt. ...

  9. android标尺自定义view,android尺子的自定义view——RulerView详解

    项目中用到自定义尺子的样式: 原效果为 因为跟自己要使用的view稍有不同 所以做了一些修改,修改的注释都放在代码中了,特此记录一下. 首先是一个自定义View: public class RuleV ...

最新文章

  1. Python : IndentationError: expected an indented block
  2. Load Runner测试脚本(tuxedo服务)的编写指南
  3. 360数科 CTO 王继平:金融 IT 变革浪潮下,360数科的技术破局
  4. php修改ip6地址为ip4,CentOS7 设置静态IPv6/IPv4地址
  5. spring boot api文档_Spring Boot: Spring Doc生成OpenAPI3.0文档
  6. 如何在Mac上恢复已删除或丢失的分区
  7. mybatis将字段改为null_【MyBatis入门到入土精讲】MyBatis介绍
  8. 怎么用计算机画图工具,使用电脑自带画图工具(画图软件怎样操作的方法
  9. thinkphp6+vue前后端分离开发验证码总是验证不正确问题
  10. matlab 计算对数似然相似度
  11. 安装office未能启动服务器,Office 2010安装时遇到1920错误问题怎么解决?
  12. 5G聚合路由器有哪些优势?能应用在哪些场景?
  13. 3岁女儿被骑摩托车男子一把抱走警方贴出寻人启事
  14. Oracle学习——dmp文件(表)导入与导出
  15. 微信公众号小程序外卖返利分销系统美团饿了么外卖cps软件源码
  16. 微信小程序-灰度发布
  17. jsf<h:outpytText>实现换行
  18. 4计算机硬件由,计算机硬件系统由(4)大部分组成,其中存储器是硬件系统中的记忆设备,(5)。A.运算器、控制器、存储器、...
  19. 使用flex 布局让子元素 左右间距相等
  20. STA series --- 8.Timing Verification (PARTII)

热门文章

  1. Java语言学习第一周周报
  2. # yyyymmdd 转 yyyy--MM--dd HH:MM:SS #
  3. PS滤镜怎么调色,可以用ps滤镜插件调色
  4. 超融合服务器怎么上传文件,服务器虚拟化 超融合
  5. 推荐一本LTE入门的优秀书籍
  6. SketchUp:解决修改不同模型背景天空颜色的问题图文教程
  7. 需求工程期末知识点复习
  8. 白酒能存放多久?有保质期吗?
  9. kettle 查询数据库写入文件_ETL KETTLE 读取csv文件写入数据库
  10. iframe标签的使用