通过WhatsApp共享原始资源(无SD卡)

时间:2018-06-23 19:31:22

标签: java android android-studio

我试图从应用程序共享mp3音频,问题是,音频发送时没有格式,我阅读了有关将其保存到外部存储器然后再共享的信息,但是我没有外部存储器,有一种方法像将其保存到内部存储器之类的东西?谢谢。这是代码:

Intent sendIntent = new Intent(Intent.ACTION_SEND);
            sendIntent.setType("audio/mpeg3");
            sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Los simuladores");
            sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("android.resource://arg.com.cevascoit.botoneralossimuladores/" + R.raw.teagachas));
            startActivity(Intent.createChooser(sendIntent, getString(R.string.app_name)));

            return false;

1 个答案:

答案 0 :(得分:0)

使用本示例中的FileProvider:

首先在内部存储中创建一个文件(例如您的mp3文件)

File sharedDir = new File(getFilesDir(), "shared");
if (!sharedDir.exists())
   sharedDir.mkdir();

File fileToShare = new File(sharedDir, "hello_world.txt");

Writer writer = new OutputStreamWriter(new FileOutputStream(fileToShare));
writer.write("Hello World");
writer.close();

然后在清单中定义FileProvider

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

然后在filepaths.xml中指定要共享的目录

<files-path
      name="shared files"
      path="shared/" />

为文件创建URI

Uri uri = FileProvider.getUriForFile(this, "ese.fileprovider", fileToShare);

共享文件

Intent shareFile = new Intent(Intent.ACTION_SEND);

shareFile.setType("application/pdf");
shareFile.putExtra(Intent.EXTRA_STREAM, uri);
shareFile.putExtra(Intent.EXTRA_SUBJECT, "Sharing " + fileToShare.getName());
shareFile.putExtra(Intent.EXTRA_TEXT, "Sharing File");

startActivity(Intent.createChooser(shareFile, "Share File"));