Last active
June 18, 2024 05:31
-
-
Save RikkaW/0ae7f51117768a03c6581c956d75958c to your computer and use it in GitHub Desktop.
insert general file with MediaStore
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Context context = view.getContext(); | |
ContentResolver cr = context.getContentResolver(); | |
ContentValues values; | |
try { | |
// create a file for test | |
File file = new File(context.getFilesDir(), "1234568"); | |
file.createNewFile(); | |
try (OutputStream os = new FileOutputStream(file)) { | |
os.write("test".getBytes()); | |
} | |
values = new ContentValues(); | |
String displayName = "test_" + System.currentTimeMillis() + ".txt"; | |
if (Build.VERSION.SDK_INT >= 29) { | |
// RELATIVE_PATH is limited, e.g., for MediaStore.Downloads the only option is DIRECTORY_DOWNLOADS | |
values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS + "/test"); | |
values.put(MediaStore.MediaColumns.IS_PENDING, true); | |
} else { | |
// on lower system versions the folder must exists, but you can use old-school method instead ("new File") | |
values.put(MediaStore.MediaColumns.DATA, Environment.getExternalStorageDirectory() + "/" + Environment.DIRECTORY_DOWNLOADS + "/test/" + displayName); | |
} | |
values.put(MediaStore.MediaColumns.DISPLAY_NAME, displayName); | |
Uri target; | |
if (Build.VERSION.SDK_INT >= 29) { | |
target = MediaStore.Downloads.EXTERNAL_CONTENT_URI; | |
} else { | |
target = MediaStore.Files.getContentUri("external"); | |
} | |
Uri uri = cr.insert(target, values); | |
if (uri == null) { | |
return; | |
} | |
InputStream is = new FileInputStream(file); | |
OutputStream os = cr.openOutputStream(uri, "rw"); | |
byte[] b = new byte[8192]; | |
for (int r; (r = is.read(b)) != -1; ) { | |
os.write(b, 0, r); | |
} | |
os.flush(); | |
os.close(); | |
is.close(); | |
if (Build.VERSION.SDK_INT >= 29) { | |
values = new ContentValues(); | |
values.put(MediaStore.Images.ImageColumns.IS_PENDING, false); | |
cr.update(uri, values, null, null); | |
} | |
} catch (Throwable tr) { | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment