I am using the following function for making request and decoding URI from onActivity result . The following function works but freezes the whole screen for many seconds before generating the final file:
// Request code:
fun filePickerRequest3SAF(activity: AppCompatActivity) {
RequestIntentBuilder(IntentInit.OPEN_DOCUMENT) // Intent(Intent.ACTION_OPEN_DOCUMENT)
.addOpenableCategory()//requestIntent.addCategory(Intent.CATEGORY_OPENABLE)
.setFilteringMimeType("video/*")
.addFlagForReadPermission() //requestIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) and requestIntent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION)
.buildAndStartActivityForResult(activity)
}
//response function. here I pass received intent's URI and activity context
fun getPathFromUriOrEmpty(uri: Uri?, context: Context?): String {
if (context == null || uri == null) return ""
return getFileFromUriOrDefault(uri, context)?.path ?: ""
}
fun getFileFromUriOrDefault(uri: Uri?, context: Context?, default:File? = null): File? {
if (context == null || uri == null) return default
val resolver = context.contentResolver
val tmpFile = File(context.cacheDir, getFileNameFromUriOrNull(uri, resolver) ?: "temp_file_name.${getExtensionFromUriOrDefault(uri, context)}")
return try {
val inputStream = context.contentResolver.openInputStream(uri)
val outputStream = FileOutputStream(tmpFile)
outputStream.use { fileOut -> inputStream?.copyTo(fileOut) }
tmpFile
} catch (t: Throwable) {
t.printStackTrace()
default
}
}
is there a way to do it better, apart from just making a file and copying it as whole? My app is supposed to upload videos of size > 1-2 gb, so is there a way we can provide the URI / file to the upload service without actually making a copy of file? I am assuming the file upload service will also be making multiple copies to upload
Ps: I intent to support android versions KitKat to android 12/+ , so not thinking of using legacy storage or other such flags if they can be avoided with SAF as a unified solution across different android versions