当我试图打开一个文件时,应用程序崩溃了。它可以在Android Nougat下运行,但在Android Nougat上它会崩溃。只有当我试图从SD卡,而不是从系统分区打开文件时,它才会崩溃。权限问题?
示例代码:
File file = new File("/storage/emulated/0/test.txt");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "text/*");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent); // Crashes on this line
日志:
android.os.FileUriExposedException:
///storage/emulated/0/test.txt
Intent.getData ()
编辑:
当针对Android Nougat时,file:// uri不再被允许。我们应该使用content:// uri。但是,我的应用程序需要打开根目录下的文件。什么好主意吗?
如果你的targetSdkVersion是24或更高,你不能在Android 7.0+设备的intent中使用file: Uri值。
你的选择是:
将targetSdkVersion降至23或更低,或者
把你的内容放在内部存储,然后使用FileProvider使它对其他应用程序有选择性地可用
例如:
Intent i=new Intent(Intent.ACTION_VIEW, FileProvider.getUriForFile(this, AUTHORITY, f));
i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(i);
(来自这个示例项目)
我想从应用程序的作用域存储共享图像,这就是我得到这个异常的地方。我找了几个小时,终于找到了这个博客。
它有点长,所以我在这里分享要点,但我会建议你看一遍。
底线是你不能从应用程序的作用域存储中共享任何东西。同样在Android 12中,意图选择器底部对话框显示了你正在共享的图像的预览,顺便说一下,这非常酷,但它不能从作用域存储URI加载预览。
解决方案是在缓存目录中创建一个你“意图”共享的文件的副本。
val cachePath = File(externalCacheDir, "my_images/")
cachePath.mkdirs()
val bitmap = loadImageFromStorage(currentQuote.bookId)
val file = File(cachePath, "cache.png")
val fileOutputStream: FileOutputStream
try {
fileOutputStream = FileOutputStream(file)
bitmap?.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream)
fileOutputStream.flush()
fileOutputStream.close()
} catch (e: FileNotFoundException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
val cacheImageUri: Uri = FileProvider.getUriForFile(this, applicationContext.packageName + ".provider", file)
val intent = Intent(Intent.ACTION_SEND).apply {
clipData = ClipData.newRawUri(null, cacheImageUri)
putExtra(Intent.EXTRA_STREAM, cacheImageUri)
type = "image/ *"
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
startActivity(Intent.createChooser(intent, null))
这就是我如何从作用域存储加载文件
fun Context.loadImageFromStorage(path: String): Bitmap? {
try {
val file = getFile(path)
val bitmap = BitmapFactory.decodeStream(FileInputStream(file))
return bitmap
} catch (e: Exception) {
e.printStackTrace()
//Returning file from public storage in case the file is stored in public storage
return BitmapFactory.decodeStream(FileInputStream(File(path)))
}
return null
}
fun Context.getFile(path: String): File? {
val cw = ContextWrapper(this)
val directory = cw.getDir("image_dir", Context.MODE_PRIVATE)
if (!directory.exists())
directory.mkdir()
try {
val fileName = directory.absolutePath + "/" + path.split("/").last()
return File(fileName)
} catch (e: Exception) {
e.printStackTrace()
}
return null
}
最后,不要忘记更新provider_paths.xml文件
<external-cache-path name="external_cache" path="." />
<external-cache-path name="external_files" path="my_images/"/>
Xamarin的。安卓
注意:路径xml/provider_paths.xml (.axml)无法解析,即使在将xml文件夹放在资源下(也许它可以放在像Values这样的现有位置,但没有尝试),所以我采用了这个方法,目前它是有效的。测试表明,每次应用程序运行时只需要调用它一次(这是有意义的,因为它改变了主机VM的操作状态)。
注意:xml需要大写,所以Resources/ xml /provider_paths.xml
Java.Lang.ClassLoader cl = _this.Context.ClassLoader;
Java.Lang.Class strictMode = cl.LoadClass("android.os.StrictMode");
System.IntPtr ptrStrictMode = JNIEnv.FindClass("android/os/StrictMode");
var method = JNIEnv.GetStaticMethodID(ptrStrictMode, "disableDeathOnFileUriExposure", "()V");
JNIEnv.CallStaticVoidMethod(strictMode.Handle, method);
以下是我的解决方案:
在Manifest.xml
<application
android:name=".main.MainApp"
android:allowBackup="true"
android:icon="@drawable/ic_app"
android:label="@string/application_name"
android:logo="@drawable/ic_app_logo"
android:theme="@style/MainAppBaseTheme">
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
在res / xml / provider_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
在我的片段中,我有下面的代码:
Uri myPhotoFileUri = FileProvider.getUriForFile(getActivity(), getActivity().getApplicationContext().getPackageName() + ".provider", myPhotoFile);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra(MediaStore.EXTRA_OUTPUT, myPhotoFileUri);
Тhat就是你所需要的。
也不需要创造
public class GenericFileProvider extends FileProvider {}
我在Android 5.0, 6.0和Android 9.0上进行了测试,并取得了成功。
如果你的targetSdkVersion >= 24,那么我们必须使用FileProvider类来访问特定的文件或文件夹,以使其他应用程序可以访问它们。我们创建自己的类继承FileProvider,以确保我们的FileProvider不会与此处所述导入依赖项中声明的FileProviders冲突。
用content:// URI替换file:// URI的步骤:
在AndroidManifest.xml的<application>标签下添加FileProvider <provider>标签。为android:authorities属性指定唯一的权限以避免冲突,导入的依赖项可能指定${applicationId}。提供者和其他常用的授权。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
...
<application
...
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>
</application>
</manifest>
然后在res/xml文件夹中创建provider_paths.xml文件。如果一个文件夹还不存在,可能需要创建它。该文件的内容如下所示。它描述了我们希望以external_files的名称共享根文件夹(path=".")的外部存储的访问权限。
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="external_files" path="."/>
</paths>
最后一步是更改下面的代码行
Uri photoURI = Uri. fromfile (createImageFile());
来
Uri photoURI = FileProvider。getUriForFile(context, context. getapplicationcontext (). getpackagename() +”。提供者”,createImageFile ());
编辑:如果你想让系统打开你的文件,你可能需要添加以下代码行:
intent.addFlags (Intent.FLAG_GRANT_READ_URI_PERMISSION);
请参考这里解释的完整代码和解决方案。