代码之家  ›  专栏  ›  技术社区  ›  grant1842

Delphi使用AndroidFileProvider发送打开意图和带有默认android库的图像文件[副本]

  •  0
  • grant1842  · 技术社区  · 7 年前

    示例代码:

    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: file:///storage/emulated/0/test.txt在app-through之外公开 Intent.getData()

    编辑:

    当瞄准安卓Nougat时, file:// content:// 而是uri。但是,我的应用程序需要打开根目录中的文件。有什么想法吗?

    0 回复  |  直到 8 年前
        1
  •  0
  •   Suraj Bahadur    6 年前

    如果你的 targetSdkVersion >= 24 ,然后我们必须使用 FileProvider 类授予对特定文件或文件夹的访问权限,以使其他应用程序可以访问这些文件或文件夹。我们创建自己的类继承 文件提供程序 here .

    更换步骤 file:// content:// URI:

    • 添加类扩展

      public class GenericFileProvider extends FileProvider {}
      
    • 添加文件提供程序 <provider> 加入 AndroidManifest.xml <application> 标签。为 android:authorities ${applicationId}.provider 以及其他常用的权威。

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        ...
        <application
            ...
            <provider
                android:name=".GenericFileProvider"
                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>
    
    • 然后创建 provider_paths.xml 归档 res/xml (path=".") 外部文件 .
    <?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 photoURI = Uri.fromFile(createImageFile());
      

      Uri photoURI = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", createImageFile());
      
    • 编辑: 如果使用意图使系统打开文件,则可能需要添加以下代码行:

      intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
      

    here.