I used this code without a problem up to Android 10. But now under Android 11 it doesn't work anymore. I think Whatsapp can't read the mp3 in the app directory created from the raw resource.
My skills are not that good, that I understand SAF or MediaStore. I think that's the problem and general, that WhatsApp don't have permission for my app directory. So I just wan't to download it to Download/ or similiar path which would be shared storage. But how?
Target SDK is 30
My code:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"
tools:ignore="QueryAllPackagesPermission"/>
<queries>
<package android:name="com.whatsapp"/>
<package android:name="com.whatsapp.w4b"/>
</queries>
private void shareButton(int shareplayint) {
try {
String mediaPath = copyFiletoExternalStorage(shareplayint);
Intent shareMedia = new Intent();
shareMedia.setAction(Intent.ACTION_SEND);
// Content of mediaPath = /storage/emulated/0/ANdroid/data/stutz.com.swissbuttons/files/swissbuttons.mp3
Toast.makeText(getApplicationContext(), mediaPath, Toast.LENGTH_LONG).show();
shareMedia.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
shareMedia.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
shareMedia.putExtra(Intent.EXTRA_STREAM, Uri.parse(mediaPath));
shareMedia.setType("audio/*");
startActivity(Intent.createChooser(shareMedia, "senden"));
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Whatsapp isch nit installiert!", Toast.LENGTH_LONG).show();
}
}
private String copyFiletoExternalStorage(int resourceId) {
String pathSDCard = getExternalFilesDir(null) + "/swissbuttons.mp3";
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;
}
Thank you for your help!