安卓使用FileProvider.getUriForFile出现问题解决
一、由于在安卓7.0以上要进行APP的自动升级,需用到FileProvider.getUriForFile方法共享安装包,首先要在AndroidManifest.xml文件中的<application 里面添加如下(在的上一行加):条目
.
<provider
android:name=“android.support.v4.content.FileProvider”
android:authorities="com.example.myapplication.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
二、创建共享目录XML文件
注意文件名必须与xml/file_paths 一致xml是在res下建的目录,file_paths.xml是存放共享目录的内容的xml文件,内容为
<external-path name="name" path="百中教育云/temp1" />
<files-path path="." name="files_path" />
注:external-path 表示:外存SDkAr 的跟目录 path 表示共享的子目录 name 表示出现在FileProvider.getUriForFile取得的路径的代替路径变量, Uri apkUri =FileProvider.getUriForFile(MainActivity.this, "com.example.myapplication.fileprovider", file);///-----ide文件提供者名 注意方法FileProvider.getUriForFile中的第二个参数要与子条目provider条目中的这句子 android:authorities="com.example.myapplication.fileprovider" 中的双引号中内容严格一致即大小写空格数等一一对应,本人就是因为大小写不注意调试了一个午才发现。 升级安装方法函数代码如下: public void installApp(String filePath){
FileUtil.requestWritePermission(this);//注意这句子是关键给我调试了一天才发现这个是动态开启读写权限函数网上查有现成的,要不会出现软件包解析错误!!
//起初我虽然在界面创建时也引用,但是由于我先打开允许安装来源应用先弹出界面而允许文件读写界面就没有弹出,不能设置文件读写
权//限,虽然在安装方法函数中也设置读写权限但不起作用(可能是高版本不起作用),因此就显示软件包解析错误!怎么查也查不
//出,//差///点放异了,
File pFile = new File(filePath);
if (null == pFile)
return;
if (!pFile.exists())
return;
Intent intent = new Intent(Intent.ACTION_VIEW);
File file = new File(filePath);
if (Build.VERSION.SDK_INT > 24) {//大于7.0使用此方法
Uri apkUri =FileProvider.getUriForFile(MainActivity.this, "com.example.myapplication.fileprovider", file);///-----ide文件提供者名
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
}else {//小于7.0就简单了
// 由于没有在Activity环境下启动Activity,设置下面的标签
intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive");
}
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
}