如果你使用的是 Android Nougat(7.0)及以上版本,那么你需要使用 FileProvider 类来获取一个 Uri 对象,而不是直接使用 Uri.fromFile() 方法。这是因为在 Android Nougat 及以上版本中,应用程序必须使用 FileProvider 来共享文件,以保证应用程序的安全性。

以下是使用 FileProvider 获取 Uri 对象的示例代码:

  1. 在 AndroidManifest.xml 文件中添加 provider 元素:
<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/file_paths" />
</provider>
  1. 创建一个 xml 文件(例如 file_paths.xml),定义文件路径:
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="." />
</paths>
  1. 使用 FileProvider.getUriForFile() 方法获取 Uri 对象:
File file = new File(Environment.getExternalStorageDirectory(), "test.jpg");
Uri uri = FileProvider.getUriForFile(context, context.getPackageName() + ".provider", file);

其中,第一个参数是 Context 对象,第二个参数是 FileProvider 的 authority,第三个参数是要共享的文件。

注意:在使用 FileProvider.getUriForFile() 方法时,需要在 Intent 中添加 FLAG_GRANT_READ_URI_PERMISSION 和 FLAG_GRANT_WRITE_URI_PERMISSION 标志,以授予临时访问权限。例如:

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "image/*");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
Android Uri.fromFile方法报错

原文地址: https://www.cveoy.top/t/topic/xjJ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录