公司开发的Android屏幕设备升级到了11,在进行apk升级进行存储本地的过程中报错

1.首先将apk下载到项目的专属文件夹中,Android/data/包名/

2.上面这个错误就是读取该文件的Uri的时候报的错。

从 Android N 开始,将不允许在 App 间,使用 file:// 的方式,传递一个 File ,(之前的uri的获取方式)否者会抛出 FileUriExposedException的错误,会直接引发 Crash。

那么解决方案为:

1.首先在AndroidManifest.xml下面声明一个provider

<provider
    android:authorities="一般是你的包名.provider"
    android:name="android.support.v4.content.FileProvider"
    android:grantUriPermissions="true"
    android:exported="false">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/filepaths"/>
</provider>

2.然后在res的xml文件夹下创建上面提到的filepaths文件

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-cache-path   path="." name="update.apk"
         />
</paths>

「external-cache-path」表示Android/data/包名/cache, 在代码中对应为Context.getExternalCacheDir()

比如Android/data/包名/cache/imgs/dog.jpg

「path」代表Android/data/包名/cache的子目录名字,这个例子中就是imgs

「name」代表最终的文件名字,上面例子中就是dog.jpg


「external-cache-path」同样级别的标签还有很多,这个表格是对应表

files-path/data/data/<包名>/files
cache-path/data/data/<包名>/cache
external-path/storage/emulate/0
external-files-path/storage/emulate/0/Android/data/<包名>/files
external-cache-path/storage/emulate/0/Android/data/<包名>/cache

3.获取Uri时用FileProvider的方式

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
     uri = FileProvider.getUriForFile(UpdateService.this,『你的包名』+".provider",new File(filePath));}

注意:!!!

上面的第二个参数是这个方法的authority,务必和Androidmanifest中申请的一样。
    android:authorities="一般是你的包名.provider",否则会找不到这个抛空指针异常

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐