分享原始资源android

问题描述

我的原始资源中有 .mp3、.mp4 和 .jpg 文件。我想与社交应用程序共享这些文件。由于这个原因,我尝试设置文件提供程序,但没有成功。

清单:

<provider
  android:name="androidx.core.content.FileProvider"
  android:authorities="com.my.packagename.fileprovider"
  android:exported="false"
  android:grantUriPermissions="true">
  <Meta-data
      android:name="android.support.FILE_PROVIDER_PATHS"
      android:resource="@xml/paths" />
</provider>

paths.xml:

<?xml version="1.0" encoding="utf-8"?>
<paths>

<files-path name="file_path" path="."/>

<external-files-path name="external_path" path="/" />

</paths>

这是我尝试共享文件的方式(在本例中为音频):

File file = new File(mAudio.getSoundUri().getEncodedpath());
Uri soundUri = FileProvider.getUriForFile(
                getContext(),"com.my.packagename.fileprovider",file);
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("audio/mp3");
sharingIntent.putExtra(Intent.EXTRA_STREAM,mAudio.getSoundUri());
startActivity(Intent.createChooser(sharingIntent,"Send"));

mAudio 对象的 getSoundUri() 返回这样的 Uri:android.resource://com.my.packagename/raw/sound.mp3

当我运行它时,我要么没有收到任何错误,但没有显示意图并且我的活动被重建,要么我得到了这个:

java.lang.IllegalArgumentException: Failed to find configured root that contains /raw/sound.mp3

我试图从 Uri 中删除 /raw 但我得到了同样的错误

java.lang.IllegalArgumentException: Failed to find configured root that contains /sound.mp3

为什么会这样?

解决方法

为什么会这样?

资源是开发机器上的文件。它们不是设备上的文件。设备上没有资源的文件系统路径,因此 FileProvider 无法为它们提供服务。

您的两个主要选择是:

  1. 将资源复制到文件中(例如,在 getCacheDir() 中),然后使用 FileProvider 来提供文件

  2. 编写您自己的 ContentProvider 以直接提供原始资源(在 getResources() 上使用 Context 来获取 Resources 对象,然后您可以获得原始资源上的 InputStream