I just migrated my sourcecode to Androidx, since I did that my share function to share a sound is no longer working. the Logcat says:
Failed to save file: /storage/emulated/0/appfolder/testsound.mp3 (Permission denied)
This is the part where it saves the sound:
final String fileName = soundObject.getItemName() + ".mp3";
File storage = Environment.getExternalStorageDirectory();
File directory = new File(storage.getAbsolutePath() + "/appfolder/");
directory.mkdirs();
final File file = new File(directory, fileName);
InputStream in = view.getContext().getResources().openRawResource(soundObject.getItemID());
try{
Log.i(LOG_TAG, "Saving sound " + soundObject.getItemName());
OutputStream out = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer, 0, buffer.length)) != -1){
out.write(buffer, 0 , len);
}
in.close();
out.close();
} catch (IOException e){
Log.e(LOG_TAG, "Failed to save file: " + e.getMessage());
}
And this is the code where it shares the sound:
try{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1){
if (ActivityCompat.checkSelfPermission(view.getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions((Activity) view.getContext(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}else {
final String AUTHORITY = view.getContext().getPackageName() + ".fileprovider";
Uri contentUri = FileProvider.getUriForFile(view.getContext(), AUTHORITY, file);
final Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, contentUri);
intent.setType("audio/mp3");
view.getContext().startActivity(Intent.createChooser(intent, "Share sound via..."));
}
}
else {
final Intent intent = new Intent(Intent.ACTION_SEND);
Uri fileUri = Uri.parse(file.getAbsolutePath());
intent.putExtra(Intent.EXTRA_STREAM, fileUri);
intent.setType("audio/mp3");
view.getContext().startActivity(Intent.createChooser(intent, "Share sound via..."));
}
} catch (Exception e){
Log.e(LOG_TAG, "Failed to share sound: " + e.getMessage());
}
}
What do I have to change and how can I archieve that everyone no matter which Android Version he is using (minSdkVersion 16) can download and share the sound?
Sadly I'm getting many bad reviews atm because no one can share (Not even Android 9 and below eventhough they used to be able to)
Thank you
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…