android.os.FileUriExposedException:

android.os.FileUriExposedException:

当我尝试打开文件时,应用程序崩溃了。它可以在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:file:///storage/emulated/0/test.txt通过Intent.getData()暴露在app之外


编辑:


在定位Android Nougat时,file://不再允许使用URI。我们应该使用content://URI代替。但是,我的应用程序需要打开根目录中的文件。有任何想法吗?


斯蒂芬大帝
浏览 2124回答 4
4回答

智慧大石

如果您的应用面向API 24+,并且您仍然需要/需要使用file:// intents,则可以使用hacky方式禁用运行时检查:if(Build.VERSION.SDK_INT>=24){    try{       Method m = StrictMode.class.getMethod("disableDeathOnFileUriExposure");       m.invoke(null);    }catch(Exception e){       e.printStackTrace();    }}方法StrictMode.disableDeathOnFileUriExposure被隐藏并记录为:/** * Used by lame internal apps that haven't done the hard work to get * themselves off file:// Uris yet. */问题是我的应用程序不是蹩脚的,而是不希望被使用内容瘫痪://那些许多应用程序无法理解的意图。例如,使用content:// scheme打开mp3文件比在file:// scheme上打开相同的应用程序要少得多。我不想通过限制我的应用程序的功能来支付Google的设计错误。谷歌希望开发人员使用内容方案,但系统并没有为此做好准备,多年来,应用程序使用文件而不是“内容”,文件可以编辑和保存,而文件服务的内容方案不能(可以他们?)。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java
Android