简单做一个APP检测更新的小工具,有点粗糙。不能断点续传,只用为个人觉得没有必要,自己可根据大家的想法添加更多的功能,这里只是为了想我一样的初学者和比较简约的人所提供。
效果如下:
基本思路先理一理,以我的实际开发为例:首先当然要一个网络去请求我们的服务器,获得仓库中的apk版本信息和下载路径,在和自己当前的版本号进行比较,当自己的版本号小于仓库中的版本号,就提示用户下载,在根据更新等级进行下载强度操作(是否强制下载还是什么的)。在下的时候监听文件下载的Progress 来更新 notification中的进度条和进度信息等待,当下载完成后,可让用户点击(关闭通知就行)进入到安装apk界面,这样就算完成了。
本次使用了okhttp (okgo)网络框架进行下载文件,这里确定下载的是apk就不多过滤信息了,直接下载安装。
首先想到的是要用一个单例来做下载管理,我们需要传入一个context 。
Context context;
private static final AppUpdateService INSTANCE = new AppUpdateService();
private static class LazyHolder {
public static AppUpdateService getThis(Context context) {
INSTANCE.context = context;
return INSTANCE;
}
}
public static AppUpdateService getInstance(Context context) {
return LazyHolder.getThis(context);
}
初始化Notification 、notificationCompat.Builder和notificationManager
//初始化通知
private void initNotification() {
notificationManager = (NotificationManager) MyApplication.getInstance().getSystemService(Context.NOTIFICATION_SERVICE);
builder = new NotificationCompat.Builder(MyApplication.getInstance());
builder.setContentTitle("正在更新...") //设置通知标题
.setSmallIcon(R.mipmap.ic_launcher_round)
.setLargeIcon(BitmapFactory.decodeResource(MyApplication.getInstance().getResources(), R.mipmap.ic_launcher_round)) //设置通知的大图标
.setDefaults(Notification.DEFAULT_LIGHTS) //设置通知的提醒方式: 呼吸灯
.setPriority(NotificationCompat.PRIORITY_MAX) //设置通知的优先级:最大
.setAutoCancel(false)//设置通知被点击一次是否自动取消
.setContentText("下载进度:" + "0%")
.setProgress(100, 0, false);
notification = builder.build();//构建通知对象
}
下载更新通知核心代码,可更新直接的选择是否让用户点击后安装,还是直接安装。
public void download(String url, String filePath) {
MyApplication.getInstance().okGo.<File>post(url).execute(new FileCallback() {
@Override
public void onSuccess(Response<File> response) {
File file = response.body();
Log.e("update", "onSuccess: 下载完成" + file.getPath() + file.getName());
builder.setContentTitle("下载完成")
.setContentText("点击安装")
.setAutoCancel(true);//设置通知被点击一次是否自动取消
//点击安装代码块
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.parse("file://" + file.toString()), "application/vnd.android.package-archive");
PendingIntent pi = PendingIntent.getActivity(context, 0, intent, 0);
notification = builder.setContentIntent(pi).build();
notificationManager.notify(1, notification);
//自动安装
// installApk(file);
}
//下载进度
@Override
public void downloadProgress(Progress progress) {
super.downloadProgress(progress);
Log.e("update", "downloadProgress: " + progress.fraction);
builder.setProgress(100, (int) (progress.fraction * 100), false);
builder.setContentText("