Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save juniorcesarabreu/e54bc4016f88e86429534e92516b0f89 to your computer and use it in GitHub Desktop.
Save juniorcesarabreu/e54bc4016f88e86429534e92516b0f89 to your computer and use it in GitHub Desktop.
Como criar arquivos de mídia na pasta downloads no Android 10 (API 29) - Problema do Armazenamento por escopo

https://www.venturus.org.br/acesso-a-arquivos-usando-armazenamento-por-escopo-no-android-10/

@RequiresApi(api = Build.VERSION_CODES.Q)
@NotNull
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.clear();
    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