今年的第一篇,记录下,不平凡的一年,工作还得继续,往后的道路继续前进;工作中再次碰到7.0文件共享的问题,这次是因为更新安装包,发现安装不了,然后总结了一下解决问题的经过。7.0之前打开手机内存中的某一文件,直接通过uri.fromFile,通过intent指定类型,然后启动就行,但是7.0之后就会出现问题。
以前打开文件安装包,7.0以上行不通
File file = new File(path);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
context.startActivity(intent);
解决办法
1.清单文件添加provide
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.app.test.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepaths" />
</provider>
authorities 指定一个唯一标识 包名.fileprovider,后面会用到 filepaths res文件夹下新建xml文件夹,创建一个filepaths.xml
2.创建filepaths.xml,指定共享的文件路径
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="zhiping" path="BusinessCache/Apk/" />
<!--物理路径相当于Context.getExternalStorageDirectory() + /BusinessCache/Apk/ -->
</paths>
其他共享文件路径
<files-path name = “ name ” path = “ path ” />
代表files/应用程序内部存储区域的子目录中的文件。该子目录与所返回的值相同Context.getFilesDir()。
<external-files-path name = “ name ” path = “ path ” />
代表应用程序外部存储区根目录中的文件。该子目录的根路径与所返回的值相同 Context.getExternalFilesDir(null)。
<external-cache-path name = “ name ” path = “ path ” />
代表应用程序外部缓存区域根目录中的文件。该子目录的根路径与所返回的值相同 Context.getExternalCacheDir()。
<external-media-path name= “ name” path = “ path” />
代表应用程序外部媒体区域根目录中的文件。该子目录的根路径与的第一个结果返回的值相同 Context.getExternalMediaDirs()。
3. 代码调用7.0 直接打开安装包进行安装
File file = new File(path);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Uri apkUri = FileProvider.getUriForFile(context, "com.app.test.fileprovider", file);
//对目标应用临时授权该Uri所代表的文件
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
context.startActivity(intent);
安装Apk的时候需要一个安装权限,
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
以上就是7.0 Apk 安装的解决办法, 类似的如打开系统相机拍照获取的照片,也需要通过provider进行访问。
参考链接:https://developer.android.google.cn/reference/androidx/core/content/FileProvider 小结一下,markdown编写的就是方便,初次使用,赞一个