一行代码实现版本更新

前言

每一个不停迭代的App都需要版本更新,这是刚需
版本更新可以强制或者半强制用户通过App内部更新,而不是通过应用市场

最终效果


在需要进行版本更新的位置调用下面的代码
context上下文为了显示弹窗或者通知栏
后面的boolean类型值 显示/不显示检查版本更新的toast
主要是在App刚打开时,检查到版本号与后台一致,那么就不需要更新APP
当然也不需要提示用户
但当用户在设置界面进行查看版本号时,版本号一致,也需要对用户进行提示

老实说,这边就是一个半封装的模板,拿来用来时很爽的

 new UpdateManager(context).checkUpdate(true);

基本过程

版本更新的几个步骤

Created with Raphaël 2.1.0 开始 获取版本信息 当前为最新? 结束 下载新版APK, 覆盖安装原版本 yes no

总结下来无外乎
调版本接口->弹更新提示窗->开启服务下载APK->安装Apk

编码

step1 创建一个版本更新管理类

public class UpdateManager  {

    private Context mContext;
    private ProgressDialog mDialog;

    public UpdateManager(Context context) {
        this.mContext = context;
    }

    /**
     * 检测软件更新
     * 这里通过自己的网络框架简单改写
     * 获取后台版本更新接口
     */
    public void checkUpdate(final boolean isToast) {
        String url = GET_VERSION;

        OkHttpUtils
                .get()
                .url(url)
                .build()
                .execute(new UpDateMsgCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(UpdateMsgBean bean, int id) {

                        if ("00".equals(bean.getCode())) {

                            UpdateMsgBean.DataBean.VersionInfoBean info = bean.getData().getVersionInfo();

                            if (DeviceUtil.getVersionCode(mContext) < info.getVersionCode()) {
                                App.version = info.getVersionNo();
                                showNoticeDialog(info.getVersionNo(), info.getContent());
                                App.VERSION_URL = info.getUrl();
                            } else {
                                if (isToast) {
                                    Toast.makeText(mContext, "已经是最新版本", Toast.LENGTH_SHORT).show();
                                }
                            }
                        }
                    }
                });
    }

    /**
     * 显示更新对话框
     */
    private void showNoticeDialog(String versionNo, String version_info) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("");
        builder.setMessage("版本号:\n" + versionNo + "\n\n更新提示:\n" + version_info);
        builder.setCancelable(false);
        builder.setPositiveButton("更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                mContext.startService(new Intent(mContext, DownLoadService.class));
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        Dialog noticeDialog = builder.create();
        noticeDialog.show();
    }

}

step2 后台服务 下载新版apk

public class DownLoadService extends Service {
//目标文件存储的文件夹路径
    private String destFileDir = Environment.getExternalStorageDirectory().getAbsolutePath() + File
            .separator + Constant.PACKAGE_NAME;
     //目标文件存储的文件名
    private String destFileName = Constant.APK_NAME;

    private Context mContext;
    private int preProgress = 0;
    private int NOTIFY_ID = 1000;
    private NotificationCompat.Builder builder;
    private NotificationManager notificationManager;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mContext = this;
        loadFile();
        return super.onStartCommand(intent, flags, startId);
    }
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

//下载文件
    private void loadFile() {
        initNotification();
/**
*这里也使用 自己的网络框架进行下载和进度监听
*/

        OkHttpUtils.get()
                .url(App.VERSION_URL)
                .build()
                .execute(new FileCallBack(destFileDir, destFileName) {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        LogUtils.error("下载失败");
                        cancelNotification();
                        stopSelf();
                    }

                    @Override
                    public void inProgress(float progress, long total, int id) {
                        super.inProgress(progress, total, id);
                        updateNotification((long) (progress * 100));
                        LogUtils.info(progress+"");
                    }

                    @Override
                    public void onResponse(File file, int id) {
                        LogUtils.info("下载完成");
                        cancelNotification();
                        installApk(file);
                        stopSelf();
                    }
                });
    }



//安装软件
    private void installApk(File file) {
        Uri uri = Uri.fromFile(file);
        Intent install = new Intent(Intent.ACTION_VIEW);
        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        install.setDataAndType(uri, "application/vnd.android.package-archive");
        // 执行意图进行安装
        mContext.startActivity(install);
    }


 //初始化Notification通知
    public void initNotification() {
        builder = new NotificationCompat.Builder(mContext)
                .setSmallIcon(R.mipmap.siji)
                .setContentText("0%")
                .setContentTitle("apk更新")
                .setProgress(100, 0, false);
        notificationManager = (NotificationManager) mContext.getSystemService(
                Context.NOTIFICATION_SERVICE);
        notificationManager.notify(NOTIFY_ID, builder.build());
    }

 //更新通知

    public void updateNotification(long progress) {
        int currProgress = (int) progress;
        if (preProgress < currProgress) {
            builder.setContentText(progress + "%");
            builder.setProgress(100, (int) progress, false);
            notificationManager.notify(NOTIFY_ID, builder.build());
        }
        preProgress = (int) progress;
    }

 //取消通知

    public void cancelNotification() {
        notificationManager.cancel(NOTIFY_ID);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}

最后 不要忘记注册权限 和配置service

猜你喜欢

转载自blog.csdn.net/jiushiwo12340/article/details/78891156