通过 WhatsApp 发送音频文件:
我们必须记住,要共享的媒体文件WhatsApp
必须存储在外部存储目录中,在这种情况下,您要发送存储在/raw
文件夹中的文件,因此我们必须制作一个副本,然后打算通过该文件发送该文件WhatsApp:
这是一个假设有一个文件的例子/raw/jorgesys_sound.mp3
这是使用的方法
private void sendWhatsAppAudio(){
try {
//Copy file to external ExternalStorage.
String mediaPath = copyFiletoExternalStorage(R.raw.jorgesys_sound, "jorgesys_sound.mp3");
Intent shareMedia = new Intent(Intent.ACTION_SEND);
//set WhatsApp application.
shareMedia.setPackage("com.whatsapp");
shareMedia.setType("audio/*");
//set path of media file in ExternalStorage.
shareMedia.putExtra(Intent.EXTRA_STREAM, Uri.parse(mediaPath));
startActivity(Intent.createChooser(shareMedia, "Compartiendo archivo."));
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Whatsapp no se encuentra instalado", Toast.LENGTH_LONG).show();
}
}
private String copyFiletoExternalStorage(int resourceId, String resourceName){
String pathSDCard = Environment.getExternalStorageDirectory() + "/Android/data/" + resourceName;
try{
InputStream in = getResources().openRawResource(resourceId);
FileOutputStream out = null;
out = new FileOutputStream(pathSDCard);
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();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return pathSDCard;
}
使用这种方法,您可以通过 WhatsApp 发送任何文件。
记得有权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>