图库无法在 android 7.0 上打开内容 uri 图像文件

  • 本文关键字:uri 文件 图像 android android
  • 更新时间 :
  • 英文 :


在我的应用中,我显示了帖子可能具有图像的帖子列表。当用户单击帖子图像时,创建选择器显示可用的选项,例如"照片","画廊"。我的问题是,为什么画廊不能在Android 7.0或API 24及以上打开图像?我会遇到一个错误"无法打开文件"。在API级别23及以下,我提供的实际文件路径似乎正常工作。在发布此问题之前,我确认了以下内容。感兴趣的部分是"照片"可以打开它。

  1. 我使用FileProvider获得了适当的内容URI。我的URI看起来像这样:

    内容://package.fileprovider/attachment/filename

  2. 我正在使用适当的哑剧类型。

  3. 我正在使用适当的意图和权限标志。请请参见以下代码:

intent myintent = new Intent(intent.action_view);myintent.putextra(sharecompat.extra_calling_package,getActivity()。getpackageName());myIntent.putextra(sharecompat.extra_calling_activity,getActivity()。getComponentName());

myintent.setDataandType(uri,mimeType);myintent.addflags(intent.flag_grant_read_uri_permission);startActivity(Intent.CreateChooser(myintent," open file:"));

仅适用于上面的Android API -Nougat设备

 File file = new File(String.valueOf(path), imageName+".png"); //it is image file name.
 if(Build.VERSION.SDK_INT>=24){ 
      Intent intent = new Intent();
      intent.setAction(Intent.ACTION_VIEW);
      intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //must provide
      Uri photoUri = FileProvider.getUriForFile(YourCurrentActivity.this, 
                      android.support.v4.BuildConfig.APPLICATION_ID + 
                      ".fileprovider", finalFile);
      intent.setData(photoUri);
      YourCurrentActivity.this.startActivity(intent);
 }

您可以通过将其添加到您的应用程序:

来打开文件URI
if(Build.VERSION.SDK_INT>=24){
    try{
        Method m = StrictMode.class.getMethod("disableDeathOnFileUriExposure");
        m.invoke(null);
    }catch(Exception e){
        e.printStackTrace();
    }
}

内容可能是新事物,但是在我看来,与降低API设备相比,没有足够的7.0个设备来证明这种不建议的方法的不使用。7.0设备仍然可以使用它,安静。

也许在Nougat上您需要获得用户的许可才能读写。您的代码将在n下工作。因此,请用户授予阅读许可,并检查FileProvider是否也需要。

最新更新