Updated
From Android 11, it won't allow creating folder/file in the root directory but, we can still manage folder separation with help of the public directory (It will show a deprecated warning but it will work)
fun getAbsolutePath(context: Context): File {
return File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "{YOUR_FOLDER_NAME}"))
}
Now, create the file with common directory path
val file = File(getAbsolutePath(requireContext()), "FILENAME.EXTENSION")
Older
Use this static method.
Currently I don't find any legal way to do this.
So, I was made this static method to get root or getAbsolutePath file path.
public static File getAbsoluteDir(Context ctx, String optionalPath) {
String rootPath;
if (optionalPath != null && !optionalPath.equals("")) {
rootPath = ctx.getExternalFilesDir(optionalPath).getAbsolutePath();
} else {
rootPath = ctx.getExternalFilesDir(null).getAbsolutePath();
}
// extraPortion is extra part of file path
String extraPortion = "Android/data/" + BuildConfig.APPLICATION_ID
+ File.separator + "files" + File.separator;
// Remove extraPortion
rootPath = rootPath.replace(extraPortion, "");
return new File(rootPath);
}