我使用以下代码与 Android Studio 3.3.2 和 Java 共享音频文件。该文件是从/raw/文件夹中提取的。
public void funktionTeilen(String file) {
Uri uri = Uri.parse("android.resource://" + this.getPackageName() + "/raw/" + file);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("audio/mpeg3");
share.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(share, "Audio teilen"));
}
原则上,共享工作正常,但发送的文件没有文件扩展名,这当然使得大多数应用程序无法读取它。如果我手动添加文件扩展名(例如从电子邮件客户端下载后),MP3 可以正常工作。
“file”由另一个函数输入,对应于原始文件夹中的文件名。基本也找到了,不然分享过程根本就不行。
那么,如何在保留文件扩展名的情况下共享文件呢?感谢您的帮助!
更新#1
public void funktionTeilen(String Datei) {
try {
File tmpFile = new File(this.getCacheDir() + "/tmpfile.mp3");
InputStream in = getResources().openRawResource(R.raw.meise1);
FileOutputStream out = new FileOutputStream(tmpFile, true);
byte[] buff = new byte[1024];
int read = 0;
try {
while ((read = in.read(buff)) > 0) {
out.write(buff, 0, read);
}
} finally {
in.close();
out.close();
}
// Uri uri = FileProvider.getUriForFile(this, this.getPackageName(), tmpFile);
Uri uri = Uri.fromFile(tmpFile);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("audio/*");
share.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(share, "Audio teilen"));
} catch (Exception e) {
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
最佳答案
I'm using the following code to share an audio file with Android Studio 3.3.2 and Java
您正在共享资源。这是您的开发计算机上的文件。它不是设备上的文件。
In principle the sharing works fine, but the file is sent without a file extension, which of course makes it unreadable by most apps.
在 Android 中,当我们使用 Android SDK 处理资源时,资源没有文件扩展名。
So, how can I share a file with retention of the file extension?
如果您使用 FileProvider
共享实际的文件,它将具有文件扩展名。因此,将与您的资源相对应的字节复制到文件中(例如,在 getCacheDir()
中),然后设置 FileProvider
并使用 FileProvider.getUriForFile()
获取要与 EXTRA_STREAM
一起使用的 Uri
。
关于java - 使用 Android Intent 共享文件 : File extension is removed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55819594/