Reputation: 712
From API 29 Environment.getExternalStorageDirectory()
and Intent.ACTION_MEDIA_SCANNER_SCAN_FILE
are deprecated.
I used the following code to save an image file to a specific folder in internal storage :
private fun saveFile(applicationContext: Context, file: File){
val folder = "/customFolder"
try {
val destFile = File("${Environment.getExternalStorageDirectory()}${folder}/${file.name}")
FileUtils.copyFile(file,destFile)
val mediaScanIntent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
val contentUri = Uri.fromFile(file)!!
mediaScanIntent.data = contentUri
applicationContext.sendBroadcast(mediaScanIntent)
} catch (ex: IllegalArgumentException) {
} catch (ex: RuntimeException) {
}
}
Reference link for FileUtils.copyFile(File srcFile,File destFile)
- https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FileUtils.html#copyFile(java.io.File,%20java.io.File)
After updating to API 29 above code doesn't work. How to modify Environment.getExternalStorageDirectory()
and Intent.ACTION_MEDIA_SCANNER_SCAN_FILE
for API 29 ?
Upvotes: 0
Views: 2779
Reputation: 337
This will work, This will store your file in app specified folder , you can user MediaStorage as well to store img in gallery , the new functions are now getFilesDir() getExternalFilesDir(), getCacheDir(),getExternalCacheDir(),
String path = ApplicationContext.getExternalFilesDir(null)+Foldername+filename;
File file = new File(path);
file.getParentFile().mkdir();
try {
OutputStream fileOutputStream = new FileOutputStream(file);
savedBitmap.compress(CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (IOException e2) {
e2.printStackTrace();
}
Upvotes: 1