Android7.0自动更新适配 包解析异常
在Android7.0的手机上,自动更新的时候出现包解析异常,在其他的手机上没有这个问题。
原因:
Android7.0引入私有目录被限制访问和StrictModeAPI。私有目录被限制访问是指在Android7.0中为了提高应用的安全性,在7.0上应用私有目录将被限制访问。StrictModeAPI是指禁止向你的应用外公开file://URI。如果一项包含文件file://URI类型的Intent离开你的应用,则会报出异常。
解决办法:
第一步:在AndroidManifest.xml中注册provider,provider可以向应用外提供数据。
//在第二步的时候会有介绍
第二步:在res/xml中创建file_paths.xml文件。
第三步:贴出我的自动更新下载的代码
publicclassUpdateManager{ privateContextmContext; privatestaticStringsavePath; privateStringsaveFileName; privateProgressBarmProgress;//下载进度条控件 privatestaticfinalintDOWNLOADING=1;//表示正在下载 privatestaticfinalintDOWNLOADED=2;//下载完毕 privatestaticfinalintDOWNLOAD_FAILED=3;//下载失败 privateintprogress;//下载进度 privatebooleancancelFlag=false;//取消下载标志位 privateStringserverVersion;//从服务器获取的版本号 privateStringapkUrl; //privateStringapkUrl="http://liuliu.lejuhuyu.com/AndroidApk/liuliu-dashou-app-1.0.2.apk"; privateStringclientVersion;//客户端当前的版本号 privateStringupdateDescription="请更新当前最新版本";//更新内容描述信息 privateStringforceUpdate;//是否强制更新 privateStringupdate; privateVersionBeanmVersionBean; privateAlertDialogalertDialog1,alertDialog2;//表示提示对话框、进度条对话框 publicUpdateManager(Contextcontext,VersionBeanversionBean){ this.mContext=context; this.mVersionBean=versionBean; apkUrl="http://liuliu.lejuhuyu.com/AndroidApk/liuliu-dashou-app-"+versionBean.getLastVersion()+".apk"; savePath=Environment.DIRECTORY_DOWNLOADS; saveFileName=savePath+"/liuliu-dashou-app-"+versionBean.getLastVersion()+".apk"; } /**显示更新对话框*/ publicvoidshowNoticeDialog(){ serverVersion=mVersionBean.getLastVersion(); clientVersion=mVersionBean.getVersion(); L.e("apkUrl="+apkUrl); L.e("savePath="+savePath); L.e("saveFileName="+saveFileName); //forceUpdate=StringUtils.getVersion(); //forceUpdate="1"; forceUpdate=mVersionBean.getImportant(); update=mVersionBean.getUpdate(); //如果版本最新,则不需要更新 if(serverVersion.equals(clientVersion)) return; if(update.equals("2")) return; AlertDialog.Builderdialog=newAlertDialog.Builder(mContext); dialog.setTitle("发现新版本:"+serverVersion); dialog.setMessage(updateDescription); dialog.setPositiveButton("现在更新",newDialogInterface.OnClickListener(){ @Override publicvoidonClick(DialogInterfacearg0,intarg1){ //TODOAuto-generatedmethodstub arg0.dismiss(); showDownloadDialog(); } }); //是否强制更新 if(forceUpdate.equals("2")){ dialog.setNegativeButton("待会更新",newDialogInterface.OnClickListener(){ @Override publicvoidonClick(DialogInterfacearg0,intarg1){ //TODOAuto-generatedmethodstub arg0.dismiss(); } }); } alertDialog1=dialog.create(); alertDialog1.setCancelable(false); alertDialog1.show(); } /**显示进度条对话框*/ publicvoidshowDownloadDialog(){ AlertDialog.Builderdialog=newAlertDialog.Builder(mContext); dialog.setTitle("正在更新"); finalLayoutInflaterinflater=LayoutInflater.from(mContext); Viewv=inflater.inflate(R.layout.softupdate_progress,null); mProgress=(ProgressBar)v.findViewById(R.id.update_progress); dialog.setView(v); //如果是强制更新,则不显示取消按钮 //if(forceUpdate.equals("1")){ //dialog.setNegativeButton("取消",newDialogInterface.OnClickListener(){ //@Override //publicvoidonClick(DialogInterfacearg0,intarg1){ ////TODOAuto-generatedmethodstub //arg0.dismiss(); //cancelFlag=false; //} //}); //} alertDialog2=dialog.create(); alertDialog2.setCancelable(false); alertDialog2.show(); //下载apk downloadAPK(); } DownloadManagermanager; Cursorcursor; DownloadManager.Requestdown; DownloadManager.Queryquery; ContentObservercontentObserver; /**下载apk的线程*/ publicvoiddownloadAPK(){ manager=(DownloadManager)LiuLiuApplication.getContext().getSystemService(Context.DOWNLOAD_SERVICE); down=newDownloadManager.Request(Uri.parse(apkUrl)); //设置允许使用的网络类型,这里是移动网络和wifi都可以 down.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE |DownloadManager.Request.NETWORK_WIFI); //显示下载界面 down.setVisibleInDownloadsUi(true); //设置下载路径和文件名 down.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,"liuliu-dashou-app-"+mVersionBean.getLastVersion()+".apk"); down.setMimeType("application/vnd.android.package-archive"); //设置为可被媒体扫描器找到 down.allowScanningByMediaScanner(); down.setAllowedOverRoaming(false); //down.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); longid=manager.enqueue(down); query=newDownloadManager.Query().setFilterById(id); contentObserver=newContentObserver(mHandler){ @Override publicvoidonChange(booleanselfChange){ //super.onChange(selfChange); booleandownloading=true; while(downloading){ cursor=manager.query(query); try{ if(cursor!=null&&cursor.moveToFirst()){ intbytes_downloaded=cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)); intbytes_total=cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)); progress=(int)((bytes_downloaded*100)/bytes_total); mHandler.sendEmptyMessage(DOWNLOADING); if(cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS))==DownloadManager.STATUS_SUCCESSFUL){ mHandler.sendEmptyMessage(DOWNLOADED); }elseif(cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS))==DownloadManager.STATUS_FAILED){ mHandler.sendEmptyMessage(DOWNLOAD_FAILED); } } }catch(Exceptione){ e.printStackTrace(); mHandler.sendEmptyMessage(DOWNLOAD_FAILED); }finally{ if(cursor!=null){ downloading=false; cursor.close(); } } } } }; mContext.getContentResolver().registerContentObserver(Uri.parse("content://downloads/"),true,contentObserver); } /**更新UI的handler*/ privateHandlermHandler=newHandler(){ @Override publicvoidhandleMessage(Messagemsg){ //TODOAuto-generatedmethodstub switch(msg.what){ caseDOWNLOADING: mProgress.setProgress(progress); break; caseDOWNLOADED: if(alertDialog2!=null) alertDialog2.dismiss(); installAPK(); break; caseDOWNLOAD_FAILED: ToastUtil.getInstance(mContext,"网络断开,请稍候再试",false).show(); break; default: break; } } }; /**下载完成后自动安装apk*/ publicvoidinstallAPK(){ FileapkFile=newFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),"liuliu-dashou-app-"+mVersionBean.getLastVersion()+".apk"); if(!apkFile.exists()){ return; } if(Build.VERSION.SDK_INT>=24){ UriapkUri=FileProvider.getUriForFile(mContext,LiuLiuApplication.getContext().getPackageName()+".fileprovider",apkFile); Intentinstall=newIntent(Intent.ACTION_VIEW); install.addCategory(Intent.CATEGORY_DEFAULT); install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); install.setDataAndType(apkUri,"application/vnd.android.package-archive"); mContext.startActivity(install); }else{ Intentintent=newIntent(); intent.setAction(Intent.ACTION_VIEW); intent.addCategory(Intent.CATEGORY_DEFAULT); intent.setType("application/vnd.android.package-archive"); intent.setData(Uri.fromFile(apkFile)); intent.setDataAndType(Uri.fromFile(apkFile),"application/vnd.android.package-archive"); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mContext.startActivity(intent); } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。