与 android 中的其他应用共享位于 url 上的音频文件

Sharing the audio file located on an url with other apps in android

我的 android 应用程序在 amazon s3 存储桶中有 mp3 文件。我有一个 URL 来访问该音频剪辑。通过将 URL 传递给媒体播放器的数据源,我可以使用 MediaPlayer 播放音频剪辑。

我正在创建一个应用程序,它允许用户将音频剪辑从我的应用程序共享到其他 IM 应用程序,如 whatsapp。因此,我将在 Activity 上提供一个共享小部件,点击该小部件后,whatsapp 应该会打开,用户应该能够 select 一个他想与他共享音频剪辑的联系人。

为此,我需要将音频剪辑下载到本地存储系统,然后使用 ContentURI 与其他应用共享该文件。但是我无法弄清楚什么是最好的方法。

根据 Android 文档,以下代码可用于发送二进制文件:

Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, uriToImage);
shareIntent.setType("image/jpeg");
startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.send_to)));

我假设音频文件是二进制文件。所以,我使用下面的代码发送音频剪辑。

Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, uriToImage);
intent.setType("audio/mpeg3");
startActivity(intent);

看来我唯一缺少的部分是 "uriToImage"。谁能帮助我了解如何获取位于 URL 的资源的 "uriToImage"。 ?

根据 CommonsWare 的评论更新了代码。以下是更新后的代码:

Intent intent = new Intent(android.content.Intent.ACTION_SEND);
                Uri contentUri = Uri.fromFile(new File(clipAudioUrl));
                intent.putExtra(Intent.EXTRA_STREAM, contentUri);
                intent.setType("audio/mpeg");
                intent.setPackage("com.whatsapp");
                startActivity(intent);

触摸共享小部件后,Watsapp 将被直接打开(这是我想要的),但是共享出现错误 "Share failed"。我假设这是因为我使用了以下代码的 uri:

Uri contentUri = Uri.fromFile(new File(clipAudioUrl));

根据 CommonsWare 的评论,whatsapp 还希望 URI 的格式为 "file:\" 或 "content:\"

你能帮我把URL转换成"file:\"或"content:\"的格式吗?谢谢。

I will provide a share widget on the Activity and upon cliking on that widget then whatsapp should be opened

仅当用户选择 WhatsApp 时。请不要假定您的应用程序的所有用户都安装了 WhatsApp 或希望将 WhatsApp 用于您应用程序中的所有内容。

For this I need to download the audio clip to local storage system and then share the file with other app using ContentURI.

从技术上讲,您可以将 S3 URL 与 ACTION_SEND 一起使用,尽管这意味着 URL 是 public。

否则,使用您想要的任何方式(AWS SDK、HttpUrlConnection、OkHttp 等)将文件下载到内部存储(例如,getCacheDir()),然后使用FileProvider将其提供给其他应用程序。 FileProvider 可以给你 UriACTION_SEND 一起使用。

该解决方案很大程度上基于 CommonsWare 的建议。但是,就我而言,我没有使用 FileProvder 发送文件。相反,我使用以下代码使其工作。

public void onClick(View v) {
                    final Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
                    String audioClipFileName="shoutout.mp3";
                    shareIntent.setType("audio/mp3");
                    shareIntent.putExtra(android.content.Intent.EXTRA_STREAM, Uri.parse("file://"+"/sdcard/"+audioClipFileName));
                    shareIntent.setPackage("com.whatsapp");
                    startActivity(Intent.createChooser(shareIntent, "Share Audio Clip"));
                }

令我惊讶的是,我实际上发现我的问题是 Intent.ACTION_SEND Whatsapp 的完全重复。

我的解决方案来自对上述问题的回答。