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

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

先在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(); 
}