在Android N中打开下载的文件

时间:2016-06-18 09:01:28

标签: android android-7.0-nougat

在下载文件后,在我的应用中Android N之前,我打开它:

Intent myIntent = new Intent(Intent.ACTION_VIEW);
File myFile = new File(result);
String mime = URLConnection.guessContentTypeFromStream(new FileInputStream(myFile));
myIntent.setDataAndType(Uri.fromFile(myFile), mime);
myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(myIntent);

Android N以来,如果我使用此代码,我会按照建议here获得FileUriExposedException我应该使用FileProvider并获取如下路径:

Uri contentUri = getUriForFile(getContext(), "com.mydomain.fileprovider", newFile);

然后用:

打开它
ParcelFileDescriptor.openFile(Uri uri,String mode)

建议here,其中显示Uri: A content URI associated with a file, as returned by getUriForFile().

但是在IDE中我ParcelfileDescriptor.open...没有方法openFile() Image

仅使用File作为参数的open(),而不是uri。那我怎么能在Android N中打开文件?

注意:我不想用我的应用程序打开文件。例如,如果我下载pdf,我想用手机上安装的应用程序打开它。

1 个答案:

答案 0 :(得分:1)

  

自Android N以来,如果我使用此代码,我会收到FileUriExposedException,如此处所示,我应该使用FileProvider

那部分是正确的。您从Uri获得的getUriForFile()会进入ACTION_VIEW Intent。所以你结束了类似的事情:

File myFile = new File(result);
Uri uri = FileProvider.getUriForFile(context, YOUR_AUTHORITY, myFile);
Intent myIntent = new Intent(Intent.ACTION_VIEW, uri);
myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(myIntent);