当我试图打开一个文件时,应用程序崩溃了。它可以在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。但是,我的应用程序需要打开根目录下的文件。什么好主意吗?


当前回答

首先,你需要添加一个提供商到你的AndroidManifest

  <application
    ...>
    <activity>
    .... 
    </activity>
    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="com.your.package.fileProvider"
        android:grantUriPermissions="true"
        android:exported="false">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
    </provider>
  </application>

现在在xml资源文件夹中创建一个文件(如果使用android studio,你可以在突出显示file_paths后按Alt + Enter并选择创建一个xml资源选项)

接下来在file_paths文件中输入

<?xml version="1.0" encoding="utf-8"?>
<paths>
  <external-path path="Android/data/com.your.package/" name="files_root" />
  <external-path path="." name="external_storage_root" />
</paths>

这个例子是关于外部路径的,你可以参考这里的更多选项。 这将允许您共享该文件夹及其子文件夹中的文件。

现在剩下的就是创建意图,如下所示:

    MimeTypeMap mime = MimeTypeMap.getSingleton();
    String ext = newFile.getName().substring(newFile.getName().lastIndexOf(".") + 1);
    String type = mime.getMimeTypeFromExtension(ext);
    try {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(getContext(), "com.your.package.fileProvider", newFile);
            intent.setDataAndType(contentUri, type);
        } else {
            intent.setDataAndType(Uri.fromFile(newFile), type);
        }
        startActivityForResult(intent, ACTIVITY_VIEW_ATTACHMENT);
    } catch (ActivityNotFoundException anfe) {
        Toast.makeText(getContext(), "No activity found to open this attachment.", Toast.LENGTH_LONG).show();
    }

编辑:我在file_paths中添加了sd卡的根文件夹。我已经测试了这段代码,它确实工作。

其他回答

如果你的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);

(来自这个示例项目)

只需将下面的代码粘贴到onCreate()活动中。

StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder(); 
StrictMode.setVmPolicy(builder.build());

它将忽略URI公开。

快乐编码:-)

使用fileProvider是正确的方法。 但是你可以使用这个简单的变通方法:

警告:它将在下一次Android发布中修复 https://issuetracker.google.com/issues/37122890#comment4

替换:

startActivity(intent);

by

startActivity(Intent.createChooser(intent, "Your title"));

我刚刚做了以下如果android版本> 24

File fl = new File(url);
    Uri uri = Uri.fromFile(fl);
    Intent intent = new Intent(Intent.ACTION_VIEW);
    if (android.os.Build.VERSION.SDK_INT>=24)
    {
        Context context = getApplicationContext();
        uri = FileProvider.getUriForFile(
                context,
                context.getApplicationContext()
                        .getPackageName() + ".provider", fl);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    }
    intent.setDataAndType(uri, mimetype);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);

点击这个链接,然后https://medium.com/@ali.muzaffar/what-is-android-os- fileuriexposedexceptionand what-you-can-do-about-it 70b9eb17c6d0#.54odzsnk4

除了使用FileProvider的解决方案,还有另一种方法可以解决这个问题。简单地说

StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());

在Application.onCreate()。通过这种方式,VM忽略文件URI公开。

方法

builder.detectFileUriExposure()

启用文件暴露检查,如果我们不设置VmPolicy,这也是默认行为。

我遇到了一个问题,如果我使用content:// URI发送一些东西,一些应用程序就是不能理解它。并且不允许降低目标SDK版本。在这种情况下,我的解决方案是有用的。

更新:

正如评论中提到的,StrictMode是诊断工具,不应该用于此问题。当我在一年前发布这个答案时,许多应用程序只能接收文件uri。当我试图向它们发送FileProvider uri时,它们就崩溃了。这在大多数应用程序中都是固定的,所以我们应该使用FileProvider解决方案。