Получить разрешение к хранилищу на Android 10 не открывая окна с выбором папки
Везде вижу один и тот же пример для сохранения файлов на Android 10 и выше. При нажатии на кнопку открывается файловый менеджер, где нужно выбрать папку и сохранить в нем файл.
У меня в классе Recorder уже реализован метод записи аудио в папку с медиа. Файл сохраняется нормально. Но есть проблема: Чтобы получить доступ к хранилищу я вызываю new Intent(Intent.ACTION_CREATE_DOCUMENT) и открывается окно, где нужно выбрать папку и сохранить файл или закрыть файловый менеджер (но пользователь может не догадаться просто закрыть менеджер и это не совсем правильно лишнее окно открывать ему). В итоге у меня непонятный файл и нормальный файл, который создает метод Recorder.record(). Можно ли как-то реализовать так, чтобы на Android 10 и выше не открывая файловый менеджер можно было получить доступ к хранилищу?
public class AudioActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
**
private int FOR_ANDROID10_STORAGE = 200;
@Override
protected void onCreate(Bundle savedInstanceState) {
***
}
//Для записи аудиопотока
@OnClick(R.id.btnStartRecord)
public void onClickPlay() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/mp3");
startActivityForResult(intent, FOR_ANDROID10_STORAGE);
} else {
//Для старых версий < 10
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == FOR_ANDROID10_STORAGE) {
reCreateRecorder();
Toast.makeText(this, "Запись аудио: " + radioTitle, Toast.LENGTH_SHORT).show();
recorder.record();
isRecording = true;
btnStartRecord.setVisibility(View.GONE);
layoutTime.setVisibility(View.VISIBLE);
btnStopRecord.setVisibility(View.VISIBLE);
}
}
}
Recorder.class
public class Recorder extends AsyncTask {
private Context context;
private String urlPath;
private String recordedFileName;
private boolean isRecording = false;
public Recorder() {}
public Recorder(Context context, String url, String recordedFilePath) {
this.context = context;
this.urlPath = url;
this.recordedFileName = recordedFilePath;
}
@Override
protected Object doInBackground(Object[] objects) {
isRecording = true;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
try {
URL url = new URL(urlPath);
InputStream inputStream = url.openStream();
ContentValues values = new ContentValues();
values.put(MediaStore.Audio.Media.DISPLAY_NAME, recordedFileName);
values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/*");
values.put(MediaStore.Audio.Media.IS_PENDING, 1);
ContentResolver contentResolver = context.getContentResolver();
Uri collection = MediaStore.Audio.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
Uri item = contentResolver.insert(collection, values);
System.out.println(item.getLastPathSegment());
ParcelFileDescriptor parcelFileDescriptor = contentResolver.openFileDescriptor(item, "w", null);
OutputStream outputStream = new FileOutputStream(parcelFileDescriptor.getFileDescriptor());
FileOutputStream fos = new FileOutputStream(parcelFileDescriptor.getFileDescriptor());
byte[] buffer = new byte[4*1024];
int read;
while ((read = inputStream.read(buffer)) != -1) {
if(isCancelled())
break;
outputStream.write(buffer,0,read);
}
outputStream.flush();
outputStream.close();
inputStream.close();
fos.close();
contentResolver.update(item, values, null, null);
values.clear();
values.put(MediaStore.Audio.Media.IS_PENDING, 0);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
//Старые версии < 10
}
return null;
}
public void record()
{
File file = new File(Environment.getExternalStorageDirectory() + File.separator + AppConstants.dirName,recordedFileName);
if (file.exists()) {
file.delete();
}
this.execute();
}
}