Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Como criar arquivos de mídia na pasta downloads no Android 10 (API 29) - Problema do Armazenamento por escopo

@RequiresApi(api = Build.VERSION_CODES.Q)
public static Uri saveFileToDownload(@NotNull Context context, File file, String mimeType) throws IOException {

    ContentValues contentValues = new ContentValues();
    contentValues.put(MediaStore.Downloads.DISPLAY_NAME, file.getName());
    contentValues.put(MediaStore.Downloads.MIME_TYPE, mimeType);
    contentValues.put(MediaStore.Downloads.IS_PENDING, 1);

    final ContentResolver contentResolver = context.getContentResolver();
    final Uri collection = MediaStore.Downloads.getContentUri("external");

    // uri do futuro arquivo
    final Uri itemUri = contentResolver.insert(collection, contentValues);

    final ParcelFileDescriptor parcelFileDescriptor = contentResolver.openFileDescriptor(itemUri, "w");
    final FileOutputStream fileOutputStream = new FileOutputStream(parcelFileDescriptor.getFileDescriptor());
    final FileInputStream fileInputStream = new FileInputStream(file);

    // copia dos arquivos
    copyFile(fileInputStream, fileOutputStream);

    contentValues.put(MediaStore.Downloads.IS_PENDING, 0);
    contentResolver.update(itemUri, contentValues, null, null);

    return itemUri;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment