共享原始资源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来直接为原始资源提供服务(在Context上使用getResources()来获得Resources对象,然后可以在原始资源上获得InputStream(