I have a private folder that contains sub folders with images and videos, I need to copy that folder to Environment.DIRECTORY_PICTURES for public
val fodler = getExternalFilesDir("Folder") // contains sub folders with images and videos
val DESTINATION = Environment.getExternalStorageDirectory().toString() + File.separator + Environment.DIRECTORY_PICTURES
copyFileOrDirectory(fodler.absolutePath, DESTINATION)
private fun copyFileOrDirectory(srcDir: String, dstDir: String) {
try {
val src: File = File(srcDir)
val dst: File = File(dstDir, src.name)
if (src.isDirectory) {
val files = src.list()
val filesLength = files.size
for (i in 0 until filesLength) {
val src1 = File(src, files[i]).path
val dst1 = dst.path
copyFileOrDirectory(src1, dst1)
}
} else {
copyFile(src, dst)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
private fun copyFile(sourceFile: File, destFile: File) {
if (!destFile.getParentFile().exists()) destFile.getParentFile().mkdirs()
if (!destFile.exists()) {
destFile.createNewFile()
}
var source: FileChannel? = null
var destination: FileChannel? = null
try {
source = FileInputStream(sourceFile).getChannel()
destination = FileOutputStream(destFile).getChannel()
destination.transferFrom(source, 0, source.size())
} finally {
if (source != null) {
source.close()
}
if (destination != null) {
destination.close()
}
}
}
now I get the file "folder" (with all its content) in "Pictures" directory, visible to everyone and public, exactly what I need.
This solution works for api levels 23-29 (android:requestLegacyExternalStorage="true" for api level 29 in menifest) but it doesn't work in api level 30 because getExternalStorageDirectory() is deprecated and android:requestLegacyExternalStorage="true" in menifest doesn't work for api level 30
what will be the solution for api level 30 ?