【发布时间】:2019-10-30 12:58:56
【问题描述】:
我刚刚将我的源代码迁移到 Androidx,因为我这样做了我的共享声音的共享功能不再起作用。 Logcat 说:
Failed to save file: /storage/emulated/0/appfolder/testsound.mp3 (Permission denied)
这是保存声音的部分:
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());
}
这是它共享声音的代码:
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());
}
}
我需要改变什么?我怎样才能让每个人无论他使用哪个 Android 版本 (minSdkVersion 16) 都可以下载和分享声音?
遗憾的是,我收到了很多差评,因为没有人可以分享(即使是 Android 9 及更低版本,尽管他们曾经能够分享) 谢谢
【问题讨论】:
-
Android 10 (KitKat)Android 10 绝对不是奇巧 -
@VladyslavMatviienko 是的,我不知道我在那里做了什么:D
标签: java android permissions share manifest