Android FileProvider配置报错android.content.pm.ProviderInfo.loadXmlMetaData问题

项目中配置FileProvider,运行报错android.content.res.XmlResourceParser错误。强制更新,下载了最新的包之后打开报错:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.XmlResourceParser android.content.pm.ProviderInfo.loadXmlMetaData(android.content.pm.PackageManager, java.lang.String)' on a null object reference

根据日志定位到错误是:

Uri contentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID+".provider", apkFile);

FileProvider.getUriForFile();方法中fileprovider对象为空,因此推断出AndroidManifest.xml中provider节点下面的authority属性有问题,没有找到。既然authority不存在,肯定是配置有问题。

        <!--android:authorities="com.xxxx.xxxx.fileProvider"-->
        <!--还是建议用下面的方法,上面这种存在弊端-->
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>

还有就是在工具类哪里打开下载文件的方法,也统一用自己项目包下的BuildConfig.APPLICATION_ID  代替。

FileProvider.getUriForFile(context.getApplicationContext(), BuildConfig.APPLICATION_ID+".provider",new File(picturePath))

public synchronized static void openFile(Context context, String fileFullName) {
        File apkFile = new File(fileFullName);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//            Uri contentUri = FileProvider.getUriForFile(context, "com.xxxx.xxxx.fileprovider", apkFile);
            Uri contentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", apkFile);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        if (context.getPackageManager().queryIntentActivities(intent, 0).size() > 0) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }
    }

 

书到用时方恨少,纸上得来终觉浅。共勉!

posted @ 2020-05-09 09:47  冷冷清清风风火火是我  阅读(509)  评论(0)    收藏  举报