【问题标题】:File provider - Files not accessible even in the own app文件提供程序 - 即使在自己的应用程序中也无法访问文件
【发布时间】:2014-07-12 12:47:18
【问题描述】:

我正在实施File Provider,仔细按照文档操作,但无法使用应用程序本身的文件或共享任何文件。

添加清单,为目录共享创建 xml 文件,生成内容 uri,授予 uri 权限,尝试与缓存、外部、内部目录共享文件,但没有任何效果。

搜索了网络,但没有发现代码中缺少任何内容。

下面是代码:

清单:

 <provider
     android:name="android.support.v4.content.FileProvider"
     android:authorities="package.widget.fileprovider"
     android:exported="false"
     android:grantUriPermissions="true" >
     <meta-data
         android:name="android.support.FILE_PROVIDER_PATHS"
         android:resource="@xml/filepaths" />
  </provider>

文件路径.xml

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <cache-path name="widgetDoc" path="."/>
</paths>

GetUri:

private Uri getFileUri(Context context, String name){
        File newFile = new File(context.getCacheDir() + File.separator + StorageUtil.INTERNAL_DIR, name);
        Uri contentUri = FileProvider.getUriForFile(context, "package.widget.fileprovider", newFile);       

        return contentUri;
    }

访问 pdf 文件的代码:

Intent target = new Intent(Intent.ACTION_VIEW);
Uri uri = getFileUri(getApplicationContext(), file);
target.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
target.setDataAndType(uri,"application/pdf");
Intent intent = Intent.createChooser(target, "Choose Pdf Viewer...");
startActivity(intent);

访问图片的代码:

imageview.setImageURI(getFileUri(getApplicationContext(), file));

请帮我找出哪里出了问题,甚至无法在我自己的应用程序中使用这些文件。

提前致谢。

【问题讨论】:

  • 永远不要使用连接来创建文件路径。使用正确的File 构造函数。除此之外,您从getFileUri() 获得的Uri 值在您将它们记录到LogCat 或在调试器中查看它们时是什么样子的?
  • @CommonsWare 抱歉回复晚了。我尝试了连接和不连接。图像的 Uri 如下所示: content://com.android.sample.widget.fileprovider/sample/sample/%0A20140707%20-%20Sample.jpg
  • 强烈考虑去掉文件名中的空格。
  • 删除了空间但仍然是同样的问题:resolveUri failed on bad bitmap uri: content://com.android.sample.widget.fileprovider/sample/sample/%0AVineet_Shukla_ad.jpg
  • 去掉文件名中的换行符 (%0A)。

标签: android pdf imageview android-contentprovider android-fileprovider


【解决方案1】:

我需要在小部件中显示这些图像文件,现在如果从小部件访问图像文件,那么它会给出 IllegalArgumentException: Failed to find configured root but it is working fine with activity

理想情况下,使用setImageViewBitmap(),并确保您的图像较小(堆空间小于 1MB,例如小于 512x512)。

虽然RemoteViews 可以接受Uri,但您可以将Intent.FLAG_GRANT_READ_URI_PERMISSIONRemoteViews 关联起来以填充ImageView。而且,您不能导出您的FileProvider,因为FileProvider 不允许这样做。

您可以尝试识别用户选择的主屏幕和use grantUriPermission() 以授予主屏幕访问此Uri 的权限,但我认为该解决方案很脆弱。

【讨论】:

  • 在 remoteview 中,它甚至不允许在点击事件时打开 pdf 文件,但是它得到了标志 FLAG_GRANT_WRITE_URI_PERMISSION。
  • @VineetShukla:我建议您打开一个单独的 Stack Overflow 问题,在其中提供配置 PendingIntent 的代码,该代码与应用小部件的 RemoteViews 一起使用。
猜你喜欢
  • 1970-01-01
  • 2019-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-12
  • 2018-12-23
  • 1970-01-01
  • 2021-11-05
相关资源
最近更新 更多