Android 版本更新(AppUpdate)之-Retrofit+RxJava实现

  • 记录一次最近用Retrofit+RxJava实现的版本更新
  • 点击更新,状态栏带有下载进度
效果图
一、先看一下实现之后的具体使用方式:

1.检测是否有更新:

    /**
     * 版本更新检测
     */
    private void checkAppUpdate() {
        UpdateCheckUtil.getInstance().checkUpdate(new UpdateCheckUtil.AppUpdateCallback() {
            @Override
            public void result(boolean update, AppUpdateResponseBean bean) {
                if (null != tvCurrentVersion) {
                    tvCurrentVersion.setText(update ? "有新版本,点击更新" : String.format(getString(R.string.str_current_version), AppUtils.getAppVersionName()));
                }
                hasUpdate = update;
                if (update) {
                    mUpdateBean = bean;
                }
            }
        });
    }

2.有新版本,点击更新:

            case R.id.check_update_ll:
               if (hasUpdate) {
                    if (UpdateManager.isUpdateIng) {
                        ToastUtils.showShort("正在下载中");
                        return;
                    } else {
                        if (AppInstallUtil.isInstallApkIsExists(this)) {
                            AppInstallUtil.installApk(this);
                            return;
                        }
                    }
                    if (!TextUtils.isEmpty(mUpdateBean.DownloadUrl)) {
                        UpdateService.startUpdateService(MineActivity.this, mUpdateBean.DownloadUrl, AppInstallUtil.getInstallPath(MineActivity.this));
                        ToastUtils.showShort("开始下载");
                        return;
                    }
                }
                ToastUtils.showShort(getString(R.string.str_current_is_new_version));
                break;
二、上面的代码中涉及到的类如下:

1.UpdateCheckUtil:

/**
 * Des: 版本更新检测
 * Created by kele on 2020/8/5.
 * E-mail:984127585@qq.com
 */
public class UpdateCheckUtil {

    private final Service mService;

    private UpdateCheckUtil() {
        mService = RetrofitManager.getInstance().createService(Service.class);
    }

    private static class UpdateUtilHolder {
        private static final UpdateCheckUtil INSTANCE = new UpdateCheckUtil();
    }

    public static UpdateCheckUtil getInstance() {
        return UpdateUtilHolder.INSTANCE;
    }

    /**
     * 检测新版本
     *
     * @param cb
     */
    public void checkUpdate(final AppUpdateCallback cb) {
        if (null == cb) {
            return;
        }
        final AppUpdateRequestBean b = RequestBeanFactory.getInstance().getAppUpdateRB();
        Observable<BaseResponse<AppUpdateResponseBean>> update = mService.update(b);
        update
                .compose(ResponseTransformer.<AppUpdateResponseBean>handleResult())
                .compose(SchedulerProvider.getInstance().<AppUpdateResponseBean>applySchedulers())
                .subscribe(new Consumer<AppUpdateResponseBean>() {
                    @Override
                    public void accept(AppUpdateResponseBean bean) throws Exception {
                        if (null == cb) {
                            return;
                        }
                        if (null != bean) {
                            int vCode = AppUtils.getAppVersionCode();
                            boolean update = bean.VersionCode > vCode;
                            cb.result(update, bean);
                            return;
                        }
                        cb.result(false, null);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        if (null == cb) {
                            return;
                        }
                        cb.result(false, null);
                    }
                });
    }

    /**
     * 版本更新回调
     */
    public interface AppUpdateCallback {
        /**
         * 检测结果
         *
         * @param update 是否有新版本
         * @param bean   新版本实体
         */
        void result(boolean update, AppUpdateResponseBean bean);
    }

    /**
     * 版本更新检测接口
     */
    private interface Service {

        /**
         * 检测版本更新
         *
         * @param rBean 请求实体
         * @return
         */
        @POST(UrlUtil.AppUpdate)
        Observable<BaseResponse<AppUpdateResponseBean>> update(
                @Body AppUpdateRequestBean rBean
        );
    }
}

2.UpdateService:

/**
 * Des: 版本更新服务
 * Created by kele on 2020/7/30.
 * E-mail:984127585@qq.com
 */
public class UpdateService extends IntentService {

    private static final String TAG = UpdateService.class.getSimpleName();

    private static final int NOTIFICATION_ID = 1001;
    private static final String ACTION_DOWNLOAD = "intent_service.action.download";

    private static final String DOWNLOAD_URL = "downloadUrl";
    private static final String APK_PATH = "apkPath";

    private CompositeDisposable cd = new CompositeDisposable();
    private NotificationCompat.Builder builder;
    private NotificationManager notificationManager;

    public UpdateService() {
        super(TAG);
    }

    /**
     * 开启下载服务
     *
     * @param context 上下文
     * @param url     下载地址
     * @param apkPath apk地址
     */
    public static void startUpdateService(Context context, String url, String apkPath) {
        if (null == context) {
            return;
        }
        if (TextUtils.isEmpty(url) || TextUtils.isEmpty(apkPath)) {
            return;
        }
        Intent intent = new Intent(context, UpdateService.class);
        intent.setAction(ACTION_DOWNLOAD);
        intent.putExtra(DOWNLOAD_URL, url);
        intent.putExtra(APK_PATH, apkPath);
        context.startService(intent);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        LogUtils.e(TAG, "---onHandleIntent");
        if (intent != null) {
            String action = intent.getAction();
            if (ACTION_DOWNLOAD.equals(action)) {
                notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                builder = new NotificationCompat.Builder(this, CommonApp.CHANNEL_ID)
                        .setContentTitle("开始下载")
                        .setContentText("版本更新")
                        .setWhen(System.currentTimeMillis())
                        .setSmallIcon(R.drawable.logo)
                        .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.logo))
                        .setAutoCancel(true);

                notificationManager.notify(NOTIFICATION_ID, builder.build());

                String url = intent.getStringExtra(DOWNLOAD_URL);
                String apkPath = intent.getStringExtra(APK_PATH);
                handleUpdate(url, apkPath);
            }
        }
    }

    /**
     * 开始下载
     *
     * @param url
     * @param apkPath
     */
    private void handleUpdate(String url, String apkPath) {
        //订阅下载进度
        subscribeEvent();
        UpdateManager.getInstance().downloadApk(this, url, apkPath, cd);
    }

    /**
     * 下载进度订阅
     */
    private void subscribeEvent() {
        RxBus.getDefault().toObservable(UpdateBean.class)
                .subscribe(new Observer<UpdateBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        cd.add(d);
                    }

                    @Override
                    public void onNext(UpdateBean updateBean) {
                        int progress = (int) Math.round(updateBean.getBytesReaded() / (double) updateBean.getTotal() * 100);
                        builder
                                .setContentInfo(String.valueOf(progress) + "%")
                                .setProgress(100, progress, false);
                        LogUtils.e(TAG, "---progress=" + progress);
                        notificationManager.notify(NOTIFICATION_ID, builder.build());

                        if (updateBean.getBytesReaded() >= updateBean.getTotal()) {
                            notificationManager.cancel(NOTIFICATION_ID);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        subscribeEvent();
                    }

                    @Override
                    public void onComplete() {
                        subscribeEvent();
                    }
                });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LogUtils.e(TAG, "---onDestroy");
    }
}

不要忘记manifest中注册Service:

  <service android:name=".utils.update.service.UpdateService" />

3.UpdateManager:

/**
 * Des: 版本更新管理
 * Created by kele on 2020/7/30.
 * E-mail:984127585@qq.com
 */
public class UpdateManager {

    private UpdateApiService mApi;

    private UpdateManager() {
        init();
    }

    public static class UpDateManagerHolder {
        public static UpdateManager INSTANCE = new UpdateManager();
    }

    public static UpdateManager getInstance() {
        return UpDateManagerHolder.INSTANCE;
    }

    /**
     * 是否正在更新中
     */
    public static boolean isUpdateIng;

    private void init() {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10000, TimeUnit.MILLISECONDS)
                .addNetworkInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Response originalResponse = chain.proceed(chain.request());//对结果重新处理
                        return originalResponse
                                .newBuilder()
                                .body(new FileResponseBody(originalResponse))//将自定义的ResposeBody设置给它
                                .build();
                    }
                })
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(UrlUtil.getBaseUrl())
                .client(client)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        mApi = retrofit.create(UpdateApiService.class);
    }

    /**
     * 开始下载
     *
     * @param url
     * @return
     */
    public Observable<ResponseBody> down(String url) {
        return mApi.down(url);
    }

    /**
     * 是否需要更新,需要则下载
     *
     * @param context 上下文
     * @param url     新版本地址
     * @param apkPath 本地apk保存路径
     * @param cd      订阅关系集合,在数据传输完毕时解除订阅
     */
    public void downloadApk(final Context context, final String url, final String apkPath, final CompositeDisposable cd) {
        down(url)
                .map(new Function<ResponseBody, BufferedSource>() {
                    @Override
                    public BufferedSource apply(ResponseBody responseBody) throws Exception {
                        return responseBody.source();//获取数据缓冲源
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .subscribe(new Observer<BufferedSource>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        cd.add(d);
                        isUpdateIng = true;
                    }

                    @Override
                    public void onNext(BufferedSource bufferedSource) {
                        try {
                            writeFile(bufferedSource, new File(apkPath));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        unSubscribe(cd);
                        isUpdateIng = false;
                    }

                    @Override
                    public void onComplete() {
                        //安装apk
//                        Intent intent = new Intent(Intent.ACTION_VIEW);
//                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                        intent.setDataAndType(Uri.fromFile(new File(apkPath)), "application/vnd.android.package-archive");
//                        context.startActivity(intent);

                        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
                            Uri uri = FileProvider.getUriForFile(context, "你的包名.fileprovider", new File(apkPath));
                            AppUtils.installApp(uri);
                        } else {
                            AppUtils.installApp(apkPath);
                        }

                        unSubscribe(cd);
                        isUpdateIng = false;
                    }
                });
    }


    /**
     * 写入文件
     */
    private void writeFile(BufferedSource source, File file) throws IOException {
        if (!file.getParentFile().exists())
            file.getParentFile().mkdirs();

        if (file.exists())
            file.delete();

        BufferedSink bufferedSink = Okio.buffer(Okio.sink(file));
        bufferedSink.writeAll(source);

        bufferedSink.close();
        source.close();
    }

    /**
     * 解除订阅
     *
     * @param cd 订阅关系集合
     */
    private void unSubscribe(CompositeDisposable cd) {
        if (cd != null && !cd.isDisposed())
            cd.dispose();
    }
}

4.FileResponseBody:

/**
 * 下载文件
 * Created by lxf on 2017/3/3.
 */
public class FileResponseBody extends ResponseBody {

    private Response originalResponse;//原结果

    public FileResponseBody(Response originalResponse) {
        this.originalResponse = originalResponse;
    }

    //返回内容类型
    @Override
    public MediaType contentType() {
        return originalResponse.body().contentType();
    }

    //返回内容长度,没有则返回-1
    @Override
    public long contentLength() {
        return originalResponse.body().contentLength();
    }

    //返回缓存源,类似于io中的BufferedReader
    @Override
    public BufferedSource source() {
        return Okio.buffer(new ForwardingSource(originalResponse.body().source()) {
            long bytesReaded = 0;

            //返回读取到的长度
            @Override
            public long read(Buffer sink, long byteCount) throws IOException {
                long bytesRead = super.read(sink, byteCount);
                bytesReaded += bytesRead == -1 ? 0 : bytesRead;
                // 通过RxBus发布进度信息
                RxBus.getDefault().send(new UpdateBean(contentLength(), bytesReaded));
                return bytesRead;
            }
        });
    }
}

5.RxBus:

/**
 * Retrofit实现的RXBus
 */
public class RxBus {

    private static volatile RxBus mDefaultInstance;

    private RxBus() {
    }

    public static RxBus getDefault() {
        if (mDefaultInstance == null) {
            synchronized (RxBus.class) {
                if (mDefaultInstance == null) {
                    mDefaultInstance = new RxBus();
                }
            }
        }
        return mDefaultInstance;
    }

    private final Subject<Object> _bus = PublishSubject.create().toSerialized();

    public void send(Object o) {
        _bus.onNext(o);
    }

    public Observable<Object> toObservable() {
        return _bus;
    }

    /**
     * 根据传递的 eventType 类型返回特定类型(eventType)的 被观察者
     *
     * @param eventType 事件类型
     * @param <T>
     * @return
     */
    public <T> Observable<T> toObservable(Class<T> eventType) {
        return _bus.ofType(eventType);
    }

    /**
     * 提供了一个新的事件,根据code进行分发
     *
     * @param code 事件code
     * @param o
     */
    public void post(int code, Object o) {
        _bus.onNext(new RxEvent(code, o));

    }


    /**
     * 根据传递的code和 eventType 类型返回特定类型(eventType)的 被观察者
     * 对于注册了code为0,class为voidMessage的观察者,那么就接收不到code为0之外的voidMessage。
     *
     * @param code      事件code
     * @param eventType 事件类型
     * @param <T>
     * @return
     */
    public <T> Observable<T> toObservable(final int code, final Class<T> eventType) {
        return _bus.ofType(RxEvent.class)
                .filter(new Predicate<RxEvent>() {
                    @Override
                    public boolean test(RxEvent rxEvent) throws Exception {
                        return rxEvent.getCode() == code && eventType.isInstance(rxEvent.getObject());
                    }
                })
                .map(new Function<RxEvent, Object>() {
                    @Override
                    public Object apply(RxEvent rxEvent) throws Exception {
                        return rxEvent.getObject();
                    }
                })
                .cast(eventType);
    }

    /**
     * 判断是否有订阅者
     */
    public boolean hasObservers() {
        return _bus.hasObservers();
    }

}

6.AppInstallUtil:

/**
 * Des: APP安装工具
 * Created by kele on 2020/7/30.
 * E-mail:984127585@qq.com
 */
public class AppInstallUtil {

    private static final String TAG = AppInstallUtil.class.getSimpleName();

    /**
     * 获取安装包文件
     *
     * @param context
     * @return
     */
    public static File getInstallApkFile(Context context) {
        File file = new File(context.getExternalFilesDir("apk"), "***.apk");
        return file;
    }

    /**
     * 获取安装包文件地址
     *
     * @param context
     * @return
     */
    public static String getInstallPath(Context context) {
        File installApkFile = getInstallApkFile(context);
        if (null != installApkFile) {
            LogUtils.e(TAG, "---getInstallPath=" + installApkFile.getAbsolutePath());
            return installApkFile.getAbsolutePath();
        }
        return "";
    }

    /**
     * 安装包文件是否存在
     *
     * @param context
     * @return
     */
    public static boolean isInstallApkIsExists(Context context) {
        File installApkFile = getInstallApkFile(context);
        if (null != installApkFile) {
            if (installApkFile.isFile()) {
                return installApkFile.exists();
            }
        }
        return false;
    }

    /**
     * 清除安装包文件
     *
     * @param context
     * @return
     */
    public static boolean clearInstallApkFile(Context context) {
        File installApkFile = getInstallApkFile(context);
        if (null != installApkFile) {
            if (installApkFile.isFile()) {
                if (installApkFile.exists()) {
                    boolean delete = installApkFile.delete();
                    LogUtils.e(TAG, "---delete=" + delete);
                    return delete;
                }
            }
        }
        return false;
    }

    /**
     * 安装apk
     *
     * @param context
     */
    public static void installApk(Context context) {
        installApk(context, getInstallPath(context));
    }

    /**
     * 安装apk
     *
     * @param context
     * @param apkPath
     */
    public static void installApk(Context context, String apkPath) {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
            Uri uri = FileProvider.getUriForFile(context,  "你的包名.fileprovider", new File(apkPath));
            AppUtils.installApp(uri);
        } else {
            AppUtils.installApp(apkPath);
        }
    }
}
上面用到的依赖库:
  implementation "io.reactivex.rxjava2:rxjava:2.1.0"
  implementation 'com.squareup.retrofit2:retrofit:2.3.0'
  implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'

补充-200922

版本更新需要一个重要的权限,上面没有提到,在这里补充下:

 <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />

今天在给新项目接更新的时候,包下载完死活安装不了,就是没加这个权限的原因!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,219评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,363评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,933评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,020评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,400评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,640评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,896评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,597评论 0 199
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,327评论 1 244
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,581评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,072评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,399评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,054评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,083评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,849评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,672评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,585评论 2 270