APP更新冒险记

作者: 鹿小纯0831 | 来源:发表于2018-08-20 21:48 被阅读13次

    一、前言

    更新功能是一个App必备的初始功能,当前app的更新主要分为以下几个步骤:

    • 1、通过接口将本地版本与服务器上的版本记性比较。
    • 2、如果服务器的版本更新,则获取线上版本号、更新说明、文件大小以及文件更新地址;否则说明当前app是最新版本。
    • 3、根据apkurl,下载apk
    • 4、进行安装。
      本文对步骤1不再进行叙述,任何一个apk都有检查更新的接口,根据接口内容来判断是否更新即可。
      此设计的三个主要特点或者说最主要的部分是:
    • 使用DialogFragment代替了以往的Dialog,使更新APP界面能够显示更多内容,做更多的操作,同时也避免了Dialog带来的那些问题。
    • 使用Service,在后台进行app的更新。
    • 使用okhttp的封装工具okgo,能够进行下载、暂停、继续、取消操作,并能展示下载进度。
      结合目前我在项目中常用的几种更新模式,我做了三种更新模式:普通更新静默更新强制更新

    二、总体使用

     new AppUpdateManager
                  .Builder()
                   //当前Activity
                  .setActivity(MainActivity.this)
                  //更新地址
                  .setUpdateUrl("http://gdown.baidu.com/data/wisegame/e8235a956b670f0e/baiduwangpan_610.apk")
                  //实现httpManager接口的对象
                  .setNewVersion("1.0")
                  .setApkUpdateLog("人这一辈子,是有三次成长的。一是当你意识到这个世界上有些事并不会按照你的意愿来发展的时候,二是无论你怎么努力都会被怀疑嘲讽的时候,三是当你知道不会成功还会勇往直前的时候。")
                  .setDialogTitle("App更新历险记")
                  .build()
                  .update();
    

    三、版本更新管理器AppUpdateManager

     public static final String TAG = AppUpdateManager.class.getSimpleName();
        public static final long REFRESH_TIME = 150;  //毫秒
        /**
         * 两个必填项
         */
        private Activity mActivity;
        private String apkDownloadUrl;
        /**
         * 选填项,均有默认值
         */
        private String newVersion;//新版本
        private String apkUpdateLog;//apk更新说明
        private String dialogTitle;//dialog标题
        private int mThemeColor;//主题颜色
        @DrawableRes
        private int mTopPic;//顶部图片
        private String apkDownloadPath;//apk下载路径
        private long refreshTime;//刷新时间
    
        private boolean mOnlyWifi;//仅wifi下载
        private boolean mSilence;//静默下载
        private boolean mForce;//强制更新
    

    通过建造者模式将上述的参数设置到AppUpdateManager中。

    三、展示更新的内容

    App更新显示Dialog

    我们通过使用DialogFragment来显示更新需要的内容,以往显示更新内容都是通过Dialog来显示,Android 官方推荐使用 DialogFragment 来代替 Dialog ,可以让它具有更高的可复用性(降低耦合)和更好的便利性(很好的处理屏幕翻转的情况)。
    需要注意的问题:DialogFragment的设置宽和高失效。

     @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
            Window dialogWindow = getDialog().getWindow();
            dialogWindow.setGravity(Gravity.CENTER);
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
            lp.height = (int) (displayMetrics.heightPixels * 0.6f);
            lp.width = (int) (displayMetrics.widthPixels * 0.76f);
            dialogWindow.setAttributes(lp);
        }
    

    通过setAttributes(lp)来设置DialogFragment的宽和高。如果出现失效的情况,主要xml布局中自定义布局应该设置成match_parent,而不是wrap_content

    四、下载apk

    点击DialogFragment中的升级按钮来进行升级,通过后台服务Service来下载apk

    apk下载中……
    /**
         * 开启后台服务下载
         */
        private void downloadApp() {
            if (TextUtils.isEmpty(mAppBean.getApkDownloadUrl())) {
                Toast.makeText(this.getActivity(), "下载路径错误", Toast.LENGTH_SHORT).show();
                return;
            }
            File appDir = new File(mAppBean.getApkDownloadPath());
            if (!appDir.exists()) {
                if (!appDir.mkdirs())
                    return;
            }
            //apk所在地址:指定地址+版本号+apkName
            DownloadService.bindService(getActivity().getApplicationContext(), conn);
        }
    

    DownloadService中开启并绑定服务。

    public static void bindService(Context context, ServiceConnection connection) {
            Intent intent = new Intent(context, DownloadService.class);
            context.startService(intent);
            context.bindService(intent, connection, Context.BIND_AUTO_CREATE);
        }
    

    开启服务能够延长服务的运行时间,绑定服务能够返回一个Binder,使后台服务和前台Activity进行交互。

    public class DownloadBinder extends Binder {
            /**
             * 开始下载
             * @param updateApp
             * @param callback
             */
            public void start(AppUpdateBean updateApp, DownloadCallback callback) {
                //apk所在地址:指定地址+版本号+apkName
                httpManager = new OkGoUpdateHttpUtil();
                String target = updateApp.getApkDownloadPath() + File.separator + updateApp.getNewVersion();
                httpManager.download(updateApp.getApkDownloadUrl(), target, new DownloadService.FileDownloadCallBack(updateApp, callback));
            }
            
            /**
             * 暂停下载
             */
            public void pause(String url) {
                if (httpManager != null) {
                    isPaused = true;
                    httpManager.pause(url);
                }
            }
    
            /**
             * 继续下载
             */
            public void continued(String url) {
                if (httpManager != null) {
                    isPaused = false;
                    httpManager.continueDownload(url);
                }
            }
    
            /**
             * 取消下载
             * @param url
             */
            public void cancel(String url){
                if (httpManager != null) {
                    httpManager.remove(url);
                }
            }
    
            /**
             * 停止后台服务
             * @param conn
             */
            public void stop(ServiceConnection conn) {
                if (httpManager != null) {
                    httpManager = null;
                }
                stopSelf();
                getApplicationContext().unbindService(conn);
            }
    
            /**
             * 判断是否是暂停状态
             * @return
             */
            public boolean isPaused(){
                return isPaused;
            }
        }
    

    五、安装apk

    安装apk的时候注意适配android版本。

    public static void installApp(Activity activity, File appFile) {
            Intent intent = getInstallAppIntent(activity, appFile);
            if (activity.getPackageManager().queryIntentActivities(intent, 0).size() > 0) {
                activity.startActivityForResult(intent, REQ_CODE_INSTALL_APP);
            }
        }
    
    public static Intent getInstallAppIntent(Context context, File appFile) {
            try {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    //区别于 FLAG_GRANT_READ_URI_PERMISSION 跟 FLAG_GRANT_WRITE_URI_PERMISSION, URI权限会持久存在即使重启,直到明确的用 revokeUriPermission(Uri, int) 撤销。 这个flag只提供可能持久授权。但是接收的应用必须调用ContentResolver的takePersistableUriPermission(Uri, int)方法实现
                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
                    Uri fileUri = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".fileProvider", appFile);
                    intent.setDataAndType(fileUri, "application/vnd.android.package-archive");
                } else {
                    intent.setDataAndType(Uri.fromFile(appFile), "application/vnd.android.package-archive");
                }
                return intent;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    
     <application
            android:name=".App">
            <service android:name="com.luxiaochun.appupdateutils.downloadService.DownloadService"/>
            <provider
                android:name="com.luxiaochun.appupdateutils.AppUpdateFileProvider"
                android:authorities="${applicationId}.fileProvider"
                android:exported="false"
                android:grantUriPermissions="true">
                <meta-data
                    android:name="android.support.FILE_PROVIDER_PATHS"
                    android:resource="@xml/new_app_file_paths"/>
            </provider>
        </application>
    
    public class AppUpdateFileProvider extends FileProvider {
    }
    

    六、源码

    源码地址:https://github.com/agula5610/AppUpdateUtilsmaster
    参考:appUpdate

    相关文章

      网友评论

      本文标题:APP更新冒险记

      本文链接:https://www.haomeiwen.com/subject/htwkiftx.html