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

2019-12-10 20:08:19王冬梅

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