Android在线更新那点事儿(适配Android6.0、7.0、8.0)

Android在线更新那点事儿(适配Android6.0、7.0、8.0),第1张

概述一、前言app在线更新是一个比较常见需求,新版本发布时,用户进入我们的app,就会d出更新提示框,第一时间更新新版本app。在线更新分为以下几个步骤: 1, 通过接口获取线上版本号,versionCode 2, 比较线上的versionCode 和本地的versionCode,d出更新窗口 3, 下载APK文件(文件下载) 4,安装APK在线更新就上面几个步骤,前2步比较简单...

一、前言

app在线更新是一个比较常见需求,新版本发布时,用户进入我们的app,就会d出更新提示框,第一时间更新新版本app。在线更新分为以下几个步骤:

 1,通过接口获取线上版本号,versionCode 2,比较线上的versionCode 和本地的versionCode,d出更新窗口 3,下载APK文件(文件下载) 4,安装APK

在线更新就上面几个步骤,前2步比较简单,重要的就是后2个步骤,而由于AndroID 各个版本对权限和隐私的收归和保护,因此,会出现各种的适配问题,因此本文就总结一下app 在线更新方法和遇到的一些适配问题。

二、apk 下载

apk下载其实就是文件下载,而文件下载有很多方式:

  1,很多三方框架都有文件上传下载功能,可以借助三方框架(比如Volley,Okhttp)  2,也可以开启一个线程去下载,(可以用IntentService)  3,最简单的一种方式:AndroID SDK 其实给我们提供了下载类DownloadManager,只需要简单的配置项设置,就能轻松实现下载功能。

本文就用第三种方式,用 DownloadManager 来下载apk。

1. 使用DownloadManager 下载apk

DownloadManager 是SDK 自带的,大概流程如下:

(1)创建一个Request,进行简单的配置(下载地址,和文件保存地址等)
(2)下载完成后,系统会发送一个下载完成的广播,我们需要监听广播。
(3)监听到下载完成的广播后,根据ID查找下载的apk文件
(4)在代码中执行apk安装。

public voID downloadApk(String apkUrl,String Title,String desc) {       // fix BUG : 装不了新版本,在下载之前应该删除已有文件       file apkfile = new file(weakReference.get().getExternalfilesDir(Environment.DIRECTORY_DOWNLOADS),"test.apk");       if (apkfile != null && apkfile.exists()) {                   apkfile.delete();                 }       DownloadManager.Request request = new DownloadManager.Request(Uri.parse(apkUrl));       //设置Title       request.setTitle(Title);       // 设置描述       request.setDescription(desc);       // 完成后显示通知栏       request.setNotificationVisibility(DownloadManager.Request.VISIBIliTY_VISIBLE_NOTIFY_COMPLETED);       request.setDestinationInExternalfilesDir(weakReference.get(),Environment.DIRECTORY_DOWNLOADS,"test.apk");       //在手机SD卡上创建一个download文件夹       // Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).mkdir() ;       //指定下载到SD卡的/download/my/目录下       // request.setDestinationInExternalPublicDir("/codoon/","test.apk");       request.setMimeType("application/vnd.androID.package-archive");       //记住reqID       mReqID = mDownloadManager.enqueue(request);   }

如上代码所示,首先构建一个Request,设置下载地址,标题、描述、apk存放目录等,最后,调用mDownloadManager.enqueue(request) 开始下载。

注意:这里我们需要记住这个mReqID,因为下载完成之后,我们需要根据这个ID 去查找apk文件,然后安装apk.

2.更新下载进度

下载文件,我们一般需要知道下载的进度,在界面给用户一个友好的提示,app 更新也是一样,我们需要在界面上显示当前下载进度和总进度,让用户知道大概会等待多久。那么如果获取下载进度呢?

在下载之前,我们需要在Activity 中注册一个Observer,就是一个观察者,当下载进度变化的时候,就会通知观察者,从而更新进度。步骤如下:

1,首先我们先定义一个观察者DownloadChangeObserver来观察下载进度2,在DownloadChangeObserver 中更新UI进度,给用户提示3,下载之前,在Activity 中注册Observer

具体代码如下:
DownloadChangeObserver.class:

 class DownloadChangeObserver extends ContentObserver {        /**         * Creates a content observer.         *         * @param handler The handler to run {@link #onChange} on,or null if none.         */        public DownloadChangeObserver(Handler handler) {            super(handler);        }        @OverrIDe        public voID onChange(boolean selfChange) {            super.onChange(selfChange);            updateVIEw();        }    }

updateVIEw()方法中,查询下载进度。

 private voID updateVIEw() {        int[] bytesAndStatus = new int[]{0,0};        DownloadManager.query query = new DownloadManager.query().setFilterByID(mReqID);        Cursor c = null;        try {            c = mDownloadManager.query(query);            if (c != null && c.movetoFirst()) {                //已经下载的字节数                bytesAndStatus[0] = c.getInt(c.getColumnIndexOrThrow(DownloadManager.ColUMN_BYTES_DOWNLOADED_SO_FAR));                //总需下载的字节数                bytesAndStatus[1] = c.getInt(c.getColumnIndexOrThrow(DownloadManager.ColUMN_TOTAL_SIZE_BYTES));                //状态所在的列索引                bytesAndStatus[2] = c.getInt(c.getColumnIndex(DownloadManager.ColUMN_STATUS));            }        } finally {            if (c != null) {                c.close();            }        }        if (mUpdateListener != null) {            mUpdateListener.update(bytesAndStatus[0],bytesAndStatus[1]);        }        Log.i(TAG,"下载进度:" + bytesAndStatus[0] + "/" + bytesAndStatus[1] + "");    }

根据前面我们记录的ID去查询进度,代码中已经注释了,不再多讲。

要想获取到进度,在下载之前,还得先注册DownloadChangeObserver,代码如下:

weakReference.get().getContentResolver().registerContentObserver(Uri.parse("content://downloads/my_downloads"),true,mDownLoadChangeObserver);

3. 获取下载结果

DownloadManager在下载完成之后,会发送一个下载完成的广播DownloadManager.ACTION_DOWNLOAD_COMPLETE,我们只需要监听这个广播,收到广播后,获取apk文件安装。

定义一个广播DownloadReceiver

class DownloadReceiver extends broadcastReceiver {        @OverrIDe        public voID onReceive(final Context context,final Intent intent) {        //  安装APK        long completeDownLoadID = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID,-1);        Logger.e(TAG,"收到广播");        Uri uri;        Intent intentInstall = new Intent();        intentInstall.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);        intentInstall.setAction(Intent.ACTION_VIEW);        if (completeDownLoadID == mReqID) {           uri = mDownloadManager.getUriForDownloadedfile(completeDownLoadID);         }         intentInstall.setDataAndType(uri,"application/vnd.androID.package-archive");         context.startActivity(intentInstall);        }                }

在下载之前注册广播

 // 注册广播,监听APK是否下载完成  weakReference.get().registerReceiver(mDownloadReceiver,new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

通过上面的几个步骤,基本上就完成app在线更新功能,在AndroID 6.0以下可以正常运行。但是别忙,本文还没有结束,AndroID每一个版本都有一些改动,导致我们需要适配不同的版本,不然的话,就会出问题,结下来就看一下AndroID 6.0,7.0,8.0 的相关适配。

三、适配AndroID 6.0

通过前面讲的几个步骤,app 在线更新在6.0以下已经可以正常运行,在AndroID6.0上,安装的时候会报出以下错误:

AndroID6.0错误.png

Caused by:5 androID.content.ActivityNotFoundException:No Activity found to handle Intent { act=androID.intent.action.VIEW typ=application/vnd.androID.package-archive flg=0x10000000 }

为什么会报上面的错误,经过deBUG发现,在AndroID6.0以下和AndroID6.0上,通过DownloadManager 获取到的Uri不一样。

区别如下:(1)AndroID 6.0,getUriForDownloadedfile得到 值为: content://downloads/my_downloads/10
(2) AndroID6.0以下,getUriForDownloadedfile得到的值为:file:///storage/emulated/0/AndroID/data/packgename/files/Download/xxx.apk

可以看到,AndroID6.0得到的apk地址为:content:// 开头的一个地址,安装的时候就会报上面的错误。怎么解决呢?经过查找资料找到了解决办法:

   //通过downLoadID查询下载的apk,解决6.0以后安装的问题    public static file queryDownloadedApk(Context context,long downloadID) {        file targetApkfile = null;        DownloadManager downloader = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);        if (downloadID != -1) {            DownloadManager.query query = new DownloadManager.query();            query.setFilterByID(downloadID);            query.setFilterByStatus(DownloadManager.STATUS_SUCCESSFul);            Cursor cur = downloader.query(query);            if (cur != null) {                if (cur.movetoFirst()) {                    String uriString = cur.getString(cur.getColumnIndex(DownloadManager.ColUMN_LOCAL_URI));                    if (!TextUtils.isEmpty(uriString)) {                        targetApkfile = new file(Uri.parse(uriString).getPath());                    }                }                cur.close();            }        }        return targetApkfile;    }

代码如上所示,不通过getUriForDownloadedfile去获取Uri,通过DownloadManager.ColUMN_LOCAL_URI 这个字段去获取apk地址。

适配AndroID 6.0后,安装apk 的代码如下:

 /**     * @param context     * @param intent     */    private voID installApk(Context context,Intent intent) {        long completeDownLoadID = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID,"收到广播");        Uri uri;        Intent intentInstall = new Intent();        intentInstall.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);        intentInstall.setAction(Intent.ACTION_VIEW);        if (completeDownLoadID == mReqID) {            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { // 6.0以下                uri = mDownloadManager.getUriForDownloadedfile(completeDownLoadID);            } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { // 6.0 - 7.0                file apkfile = queryDownloadedApk(context,completeDownLoadID);                uri = Uri.fromfile(apkfile);            }             // 安装应用            Logger.e("zhouwei","下载完成了");            intentInstall.setDataAndType(uri,"application/vnd.androID.package-archive");            context.startActivity(intentInstall);        }    }

四、适配AndroID 7.0

刚适配完6.0,在7.0以上的机子上又出问题了,为什么呢?因为在AndroID 7.0上,对文件的访问权限作出了修改,不能在使用file://格式的Uri 访问文件 ,AndroID 7.0提供 fileProvIDer,应该使用这个来获取apk地址,然后安装apk。如下进行简单的适配:

(1) 在res 目录下,新建一个xml 文件夹,在xml 下面创建一个文件provIDer_paths文件:

<?xml version="1.0" enCoding="utf-8"?><paths>    <external-path        name="external"        path="" />    <external-files-path        name="Download"        path="" /></paths>

(2) 在AndroIDManifest.xml清单文件中申明ProvIDer:

<!-- AndroID 7.0 照片、APK下载保存路径-->        <provIDer            androID:name="androID.support.v4.content.fileProvIDer"            androID:authoritIEs="packgename.fileProvIDer"            androID:exported="false"            androID:grantUriPermissions="true">            <Meta-data                androID:name="androID.support.file_PROVIDER_PATHS"                androID:resource="@xml/provIDer_paths" />        </provIDer>

(3) AndroID 7.0上的文件地址获取:

 uri = fileProvIDer.getUriForfile(context,"packageNam.fileProvIDer",new file(context.getExternalfilesDir(Environment.DIRECTORY_DOWNLOADS),"xxx.apk"));

好了,就这样7.0适配工作就完成了,适配后的安装代码如下:

 /**     * @param context     * @param intent     */    private voID installApk(Context context,completeDownLoadID);                uri = Uri.fromfile(apkfile);            } else { // AndroID 7.0 以上                uri = fileProvIDer.getUriForfile(context,"packgename.fileProvIDer","xxx.apk"));                intentInstall.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);            }            // 安装应用            Logger.e("zhouwei","application/vnd.androID.package-archive");            context.startActivity(intentInstall);        }    }

注意:把上面的packageNam 换成你自己的包名,把xxx.apk 换成你自己的apk的名字。
关于更多fileProvIDer的东西,这儿就不展开讲了,想要了解的可以看一下鸿洋的文章:Android 7.0 行为变更 通过FileProvider在应用间共享文件吧
,讲的很清楚。

五、适配AndroID 8.0:未知来源的应用权限

好特么累,继续适配AndroID 8.0,由于没有AndroID 8.0的手机,一直没有注意,前些天一个华为用户反馈在线更新不了新版本,具体表现就是:apk下载完成,一闪而过,没有跳转到apk安装界面。经过排查,确定了是AndroID 8.0权限问题。

Android8.0以上,未知来源的应用是不可以通过代码来执行安装的(在sd卡中找找到apk,手动安装是可以的),未知应用安装权限的开关被除掉,取而代之的是未知来源应用的管理列表,需要列表里面开启你的应用的未知来源的安装权限。Google这么做是为了防止一开始正经的应用后来开始通过升级来做一些不合法的事情,侵犯用户权益。

知道问题了,我们就适配吧:

(1) 在清单文件中申明权限:REQUEST_INSTALL_PACKAGES

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

(2) 在代码中判断用户是否已经受过权限了,如果已经授权,可以直接安装,如果没有授权,则跳转到授权列表,让用户开启未知来源应用安装权限,开启后,再安装应用。

在监听apk下载状态的广播中添加如下代码:

boolean haveInstallPermission;            // 兼容AndroID 8.0            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {                //先获取是否有安装未知来源应用的权限                haveInstallPermission = context.getPackageManager().canRequestPackageInstalls();                if (!haveInstallPermission) {//没有权限                    // d窗,并去设置页面授权                    final AndroIDOInstallPermissionListener Listener = new AndroIDOInstallPermissionListener() {                        @OverrIDe                        public voID permissionSuccess() {                            installApk(context,intent);                        }                        @OverrIDe                        public voID permissionFail() {                            ToastUtils.shortToast(context,"授权失败,无法安装应用");                        }                    };                    AndroIDOPermissionActivity.sListener = Listener;                    Intent intent1 = new Intent(context,AndroIDOPermissionActivity.class);                    context.startActivity(intent1);                } else {                    installApk(context,intent);                }            } else {                installApk(context,intent);            }

因为授权时需要d框提示,我们用一个Activity来代理创建了一个Activity:AndroIDOPermissionActivity 来申请权限,用户点击设置后,跳转到权限设置界面,然后我们再onActivityResult 里判断是都授权成功。

AndroIDOPermissionActivity 代码如下:

/** * 兼容AndroID 8。0 APP 在线更新,权限申请界面 * Created by zhouwei on 2018/3/23. */public class AndroIDOPermissionActivity extends BaseActivity {    public static final int INSTALL_PACKAGES_REQUESTCODE = 1;    private AlertDialog mAlertDialog;    public static AppDownloadManager.AndroIDOInstallPermissionListener sListener;    @OverrIDe    protected voID onCreate(@Nullable Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        // d窗        if (Build.VERSION.SDK_INT >= 26) {            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.REQUEST_INSTALL_PACKAGES},INSTALL_PACKAGES_REQUESTCODE);        } else {            finish();        }    }    @RequiresAPI(API = Build.VERSION_CODES.O)    @OverrIDe    public voID onRequestPermissionsResult(int requestCode,@NonNull String[] permissions,@NonNull int[] grantResults) {        super.onRequestPermissionsResult(requestCode,permissions,grantResults);        switch (requestCode) {            case INSTALL_PACKAGES_REQUESTCODE:                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {                    if (sListener != null) {                        sListener.permissionSuccess();                        finish();                    }                } else {                    //startInstallPermissionSettingActivity();                    showDialog();                }                break;        }    }    private voID showDialog() {        AlertDialog.Builder builder = new AlertDialog.Builder(this);        builder.setTitle(R.string.app_name);        builder.setMessage("为了正常升级 xxx APP,请点击设置按钮,允许安装未知来源应用,本功能只限用于 xxx APP版本升级");        builder.setPositivebutton("设置",new DialogInterface.OnClickListener() {            @RequiresAPI(API = Build.VERSION_CODES.O)            @OverrIDe            public voID onClick(DialogInterface dialogInterface,int i) {                startInstallPermissionSettingActivity();                mAlertDialog.dismiss();            }        });        builder.setNegativebutton("取消",new DialogInterface.OnClickListener() {            @OverrIDe            public voID onClick(DialogInterface dialogInterface,int i) {                if (sListener != null) {                    sListener.permissionFail();                }                mAlertDialog.dismiss();                finish();            }        });        mAlertDialog = builder.create();        mAlertDialog.show();    }    @RequiresAPI(API = Build.VERSION_CODES.O)    private voID startInstallPermissionSettingActivity() {        //注意这个是8.0新API        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNowN_APP_SOURCES,Uri.parse("package:" + getPackagename()));        startActivityForResult(intent,1);    }    @OverrIDe    protected voID onActivityResult(int requestCode,int resultCode,Intent data) {        super.onActivityResult(requestCode,resultCode,data);        if (requestCode == 1 && resultCode == RESulT_OK) {            // 授权成功            if (sListener != null) {                sListener.permissionSuccess();            }        } else {            // 授权失败            if (sListener != null) {                sListener.permissionFail();            }        }        finish();    }    @OverrIDe    protected voID onDestroy() {        super.onDestroy();        sListener = null;    }}

注意:当通过Intent 跳转到未知应用授权列表的时候,一定要加上包名,这样就能直接跳转到你的app下,不然只能跳转到列表。

 

跳转未知来源应用授权.png

好了,这样AndroID 8.0 上也可以在线更新了。

六、完整代码,封装了一个类AppDownloadManager

为了不依赖于某个Activity,因此封装了一个AppDownloadManager
,少量几行代码就可以实现在线更新,给出完整代码:

public class AppDownloadManager {    public static final String TAG = "AppDownloadManager";    private WeakReference<Activity> weakReference;    private DownloadManager mDownloadManager;    private DownloadChangeObserver mDownLoadChangeObserver;    private DownloadReceiver mDownloadReceiver;    private long mReqID;    private OnUpdateListener mUpdateListener;    public AppDownloadManager(Activity activity) {        weakReference = new WeakReference<Activity>(activity);        mDownloadManager = (DownloadManager) weakReference.get().getSystemService(Context.DOWNLOAD_SERVICE);        mDownLoadChangeObserver = new DownloadChangeObserver(new Handler());        mDownloadReceiver = new DownloadReceiver();    }    public voID setUpdateListener(OnUpdateListener mUpdateListener) {        this.mUpdateListener = mUpdateListener;    }    public voID downloadApk(String apkUrl,String desc) {        // fix BUG : 装不了新版本,在下载之前应该删除已有文件        file apkfile = new file(weakReference.get().getExternalfilesDir(Environment.DIRECTORY_DOWNLOADS),"app_name.apk");        if (apkfile != null && apkfile.exists()) {            apkfile.delete();        }        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(apkUrl));        //设置Title        request.setTitle(Title);        // 设置描述        request.setDescription(desc);        // 完成后显示通知栏        request.setNotificationVisibility(DownloadManager.Request.VISIBIliTY_VISIBLE_NOTIFY_COMPLETED);        request.setDestinationInExternalfilesDir(weakReference.get(),"app_name.apk");        //在手机SD卡上创建一个download文件夹        // Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).mkdir() ;        //指定下载到SD卡的/download/my/目录下        // request.setDestinationInExternalPublicDir("/codoon/","codoon_health.apk");        request.setMimeType("application/vnd.androID.package-archive");        //        mReqID = mDownloadManager.enqueue(request);    }    /**     * 取消下载     */    public voID cancel() {        mDownloadManager.remove(mReqID);    }    /**     * 对应 {@link Activity }     */    public voID resume() {        //设置监听Uri.parse("content://downloads/my_downloads")        weakReference.get().getContentResolver().registerContentObserver(Uri.parse("content://downloads/my_downloads"),mDownLoadChangeObserver);        // 注册广播,监听APK是否下载完成        weakReference.get().registerReceiver(mDownloadReceiver,new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));    }    /**     * 对应{@link Activity#onPause()} ()}     */    public voID onPause() {        weakReference.get().getContentResolver().unregisterContentObserver(mDownLoadChangeObserver);        weakReference.get().unregisterReceiver(mDownloadReceiver);    }    private voID updateVIEw() {        int[] bytesAndStatus = new int[]{0,"下载进度:" + bytesAndStatus[0] + "/" + bytesAndStatus[1] + "");    }    class DownloadChangeObserver extends ContentObserver {        /**         * Creates a content observer.         *         * @param handler The handler to run {@link #onChange} on,or null if none.         */        public DownloadChangeObserver(Handler handler) {            super(handler);        }        @OverrIDe        public voID onChange(boolean selfChange) {            super.onChange(selfChange);            updateVIEw();        }    }    class DownloadReceiver extends broadcastReceiver {        @OverrIDe        public voID onReceive(final Context context,final Intent intent) {            boolean haveInstallPermission;            // 兼容AndroID 8.0            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {                //先获取是否有安装未知来源应用的权限                haveInstallPermission = context.getPackageManager().canRequestPackageInstalls();                if (!haveInstallPermission) {//没有权限                    // d窗,并去设置页面授权                    final AndroIDOInstallPermissionListener Listener = new AndroIDOInstallPermissionListener() {                        @OverrIDe                        public voID permissionSuccess() {                            installApk(context,intent);            }        }    }    /**     * @param context     * @param intent     */    private voID installApk(Context context,"package_name.fileProvIDer","app_name.apk"));                intentInstall.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);            }            // 安装应用            Logger.e("zhouwei","application/vnd.androID.package-archive");            context.startActivity(intentInstall);        }    }    //通过downLoadID查询下载的apk,解决6.0以后安装的问题    public static file queryDownloadedApk(Context context,long downloadID) {        file targetApkfile = null;        DownloadManager downloader = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);        if (downloadID != -1) {            DownloadManager.query query = new DownloadManager.query();            query.setFilterByID(downloadID);            query.setFilterByStatus(DownloadManager.STATUS_SUCCESSFul);            Cursor cur = downloader.query(query);            if (cur != null) {                if (cur.movetoFirst()) {                    String uriString = cur.getString(cur.getColumnIndex(DownloadManager.ColUMN_LOCAL_URI));                    if (!TextUtils.isEmpty(uriString)) {                        targetApkfile = new file(Uri.parse(uriString).getPath());                    }                }                cur.close();            }        }        return targetApkfile;    }    public interface OnUpdateListener {        voID update(int currentByte,int totalByte);    }    public interface AndroIDOInstallPermissionListener {        voID permissionSuccess();        voID permissionFail();    }}

使用就很简单了,如下:

(1) d出更新提示框:提示用户更新

 private voID showUpdateDialog(final AppUpdateInfo updateInfo) {        AppUpdateDialog dialog = new AppUpdateDialog(getContext());        dialog.setAppUpdateInfo(updateInfo);        dialog.setonUpdateClickListener(new AppUpdateDialog.OnUpdateClickListener() {            @OverrIDe            public voID update(final AppUpdateDialog updateDialog) {                String Title = "app name";                String desc = "版本更新";                mDownloadManager.setUpdateListener(new AppDownloadManager.OnUpdateListener() {                    @OverrIDe                    public voID update(int currentByte,int totalByte) {                        updateDialog.setProgress(currentByte,totalByte);                        if ((currentByte == totalByte) && totalByte != 0) {                            updateDialog.dismiss();                        }                    }                });                mDownloadManager.downloadApk(updateInfo.download_url,Title,desc);            }        });        dialog.setCanceledOntouchOutsIDe(false);        dialog.setCancelable(false);        dialog.show();    }

(2) 注意在 onResume 和 onPause 调用对应方法:

 @OverrIDe    public voID onResume() {        super.onResume();        if (mDownloadManager != null) {            mDownloadManager.resume();        }}
 @OverrIDe    public voID onPause() {        super.onPause();        if (mDownloadManager != null) {            mDownloadManager.onPause();        }    }

app更新.png

七、总结

本文总结了项目中app在线更新遇到的一些适配问题,关于AndroID 6.0 的适配,如果你没有使用DownloadManager,可能不会遇到这个问题。7.0 和 8.0 的适配不管用哪种方式,都会有。

 

附:AppUpdateDialog代码,其实没啥参考的,就一个自定义Dialog,我还是贴出来吧

public class AppUpdateDialog extends headerBaseDialog implements VIEw.OnClickListener {    private String mContent;    private AppUpdateInfo mAppUpdateInfo;    private OnUpdateClickListener mOnUpdateListener;    private Progressbar mProgressbar;    private TextVIEw mValueText;    private boolean mForceUpdate = true;    public AppUpdateDialog(@NonNull Context context) {        super(context);    }    public voID setContent(String mContent) {        this.mContent = mContent;    }    public voID setAppUpdateInfo(AppUpdateInfo mAppUpdateInfo) {        this.mAppUpdateInfo = mAppUpdateInfo;    }    public voID setProgress(int progress,int maxValue) {        if (maxValue == 0) {            return;        }        mProgressbar.setMax(maxValue);        mProgressbar.setProgress(progress);        mValueText.setText((int) (progress * 1.0f / maxValue * 100) + "%");    }    public voID setonUpdateClickListener(OnUpdateClickListener mOnUpdateListener) {        this.mOnUpdateListener = mOnUpdateListener;    }    @OverrIDe    protected voID initVIEw() {        setCanceledOntouchOutsIDe(false);        if (mAppUpdateInfo.force_update) {            mForceUpdate = true;        } else {            mForceUpdate = false;        }        TextVIEw textVIEw = (TextVIEw) findVIEwByID(R.ID.app_update_content);        TextVIEw version = (TextVIEw) findVIEwByID(R.ID.app_update_version);        mProgressbar = (Progressbar) findVIEwByID(R.ID.app_update_progress);        mValueText = (TextVIEw) findVIEwByID(R.ID.app_update_current_percent);        version.setText(mAppUpdateInfo.version + " 更新内容");        textVIEw.setText(mAppUpdateInfo.note);        TextVIEw btnUpdate = (TextVIEw) findVIEwByID(R.ID.btn_app_update);        btnUpdate.setText("更新");        btnUpdate.setonClickListener(this);    }    @OverrIDe    protected int getheaderLayout() {        return R.layout.app_update_header_layout;    }    @OverrIDe    protected int getContentLayout() {        return R.layout.app_update_content_layout;    }    @OverrIDe    protected Drawable getBgDrawable() {        return null;    }    @OverrIDe    protected int getStartcolor() {        return getContext().getResources().getcolor(R.color.body_weight_start_color);    }    @OverrIDe    protected int getEndcolor() {        return getContext().getResources().getcolor(R.color.body_weight_end_color);    }    @OverrIDe    protected boolean isShowClose() {        return !mForceUpdate;    }    @OverrIDe    public voID onClick(VIEw v) {        // update        if (mOnUpdateListener != null) {            findVIEwByID(R.ID.update_progress_layout).setVisibility(VIEw.VISIBLE);            findVIEwByID(R.ID.btn_app_update).setVisibility(VIEw.GONE);            mOnUpdateListener.update(this);        }    }    public interface OnUpdateClickListener {        voID update(AppUpdateDialog dialog);    }}

 

总结

以上是内存溢出为你收集整理的Android在线更新那点事儿(适配Android6.0、7.0、8.0)全部内容,希望文章能够帮你解决Android在线更新那点事儿(适配Android6.0、7.0、8.0)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/web/1089438.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-27
下一篇 2022-05-27

发表评论

登录后才能评论

评论列表(0条)

保存