我在 Android 10 之前使用此代码没有问题。但现在在 Android 11 下它不再工作了。我认为 Whatsapp 无法读取从原始资源创建的应用目录中的 mp3。
我的技能不是很好,我了解 SAF 或 MediaStore。我认为这是问题所在,一般来说,WhatsApp 没有我的应用目录的权限。所以我只是不想将它下载到 Download/ 或类似的共享存储路径。但是怎么做?
目标 SDK 为 30
我的代码:
<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;
}
谢谢您的帮助!