2023年11月26日发(作者:)

Android实现APP⾃动更新功能

现在⼀般的android软件都是需要不断更新的,当你打开某个app的时候,如果有新的版本,它会提⽰你有新版本需要更新。该

⼩程序实现的就是这个功能。

该⼩程序的特点是,当有更新时,会弹出⼀个提⽰框,点击确定,则在通知来创建⼀个进度条进⾏下载,点击取消,则取消更

新。

以下是详细代码:

1.创建布局⽂件notification_,⽤于在通知栏⽣成⼀个进度条和下载图标。

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:padding="3dp" >

android:id="@+id/notificationImage"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

@Override

public void onCreate() {

// TODO Auto-generated method stub

te();

appInstance = this;

context = eContext();

// // 获取当前版本号

// try {

// PackageInfo packageInfo = getApplicationContext()

// .getPackageManager().getPackageInfo(getPackageName(), 0);

// ersion = nCode;

// Version = 1;// 假定服务器版本为2,本地版本默认是1

// } catch (NameNotFoundException e) {

// tackTrace();

// }

initGlobal();

}

public void initGlobal() {

try {

ersion = getPackageManager().getPackageInfo(

getPackageName(), 0).versionCode; // 设置本地版本号

Version = 2;// 假定服务器版本为2,本地版本默认是1--实际开发中是从服务器获取最新版本号,android具体与后端的交互见我另///外的博⽂

} catch (Exception ex) {

tackTrace();

}

}

}

3.创建配置⽂件类,在这个类⾥⾯定义⼀些与版本相关的常量

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 = Extra("titleId", 0);

// 创建⽂件

if (_(nment

.getExternalStorageState())) {

updateDir = new File(ernalStorageDirectory(),

leName);

estEventInfo(,

"QQ", "下载完成,点击安装。", updatePendingIntent);

(0, updateNotification);

// 停⽌服务

stopService(updateIntent);

case DOWNLOAD_FAIL:

// 下载失败

estEventInfo(,

"QQ", "下载完成,点击安装。", updatePendingIntent);

(0, updateNotification);

default:

stopService(updateIntent);

}

}

};

();

}

}

return totalSize;

}

class updateRunnable implements Runnable {

Message message = Message();

public void run() {

= DOWNLOAD_COMPLETE;

try {

le("软件升级")

.setMessage("发现新版本,建议⽴即更新使⽤.")

.setPositiveButton("更新",

new kListener() {

public void onClick(DialogInterface dialog,

int which) {

// 开启更新服务UpdateService

// 这⾥为了把update更好模块化,可以传⼀些updateService依赖的值

// 如布局ID,资源ID,动态获取的标题,这⾥以app_name为例

Intent updateIntent = new Intent(

,

);

ra("titleId",

_name);

startService(updateIntent);

}

})

.setNegativeButton("取消",

new kListener() {

public void onClick(DialogInterface dialog,

int which) {

s();

}

});

().show();

} else {

// 清理⼯作,略去

// cheanUpdateFile()

}

}

}

6.添加权限以及将服务静态加载(在配置⽂件中加载)