Created
March 3, 2024 11:32
-
-
Save khaledahmedelsayed/7c0aef1632411344db9310dd283d9b79 to your computer and use it in GitHub Desktop.
File Multiple Selector Helper
This file contains hidden or 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
import android.Manifest | |
import android.net.Uri | |
import android.os.Build | |
import androidx.activity.result.ActivityResultLauncher | |
import androidx.activity.result.contract.ActivityResultContracts | |
import androidx.fragment.app.Fragment | |
class FileMultipleSelectorHelper( | |
fragment: Fragment, | |
val fileDataType: Companion.FileDataType, | |
maxFileSizeInBytesValidation : Int? = null, | |
onMultipleFilesSelected: (List<ByteArray?>, List<Uri?>, isAnyInvalidFileSize : Boolean) -> Unit | |
) : FileSelectorHelper(fragment, fileDataType, maxFileSizeInBytesValidation, { _, _, _->}) { | |
private val galleryLauncher: ActivityResultLauncher<Array<String>> | |
init { | |
with(fragment) { | |
galleryLauncher = | |
registerForActivityResult( | |
ActivityResultContracts.OpenMultipleDocuments() | |
) { listOfUris -> | |
val listOfFileBytes = listOfUris.map { uri -> uri.let { requireContext().contentResolver.openInputStream(uri)?.readBytes() } } | |
val isAnyInvalidFileSize = listOfFileBytes.any { (it?.size ?: 0) > (maxFileSizeInBytesValidation ?: Int.MAX_VALUE) } | |
if (listOfFileBytes.isNotEmpty()) | |
onMultipleFilesSelected.invoke(listOfFileBytes, listOfUris, isAnyInvalidFileSize) | |
} | |
galleryPermissionLauncher = registerForActivityResult( | |
ActivityResultContracts.RequestMultiplePermissions() | |
) { | |
if (it.all { it.value }) | |
galleryLauncher.launch(fileDataType.supportedTypesIntents.toTypedArray()) | |
} | |
} | |
} | |
override fun openGallery() { | |
checkStoragePermission().let { hasStoragePermission -> | |
if (hasStoragePermission) | |
galleryLauncher.launch(fileDataType.supportedTypesIntents.toTypedArray()) | |
else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) // -> https://developer.android.com/about/versions/13/behavior-changes-13#granular-media-permissions | |
galleryPermissionLauncher.launch(arrayOf(Manifest.permission.READ_MEDIA_IMAGES, Manifest.permission.READ_MEDIA_VIDEO)) | |
else | |
galleryPermissionLauncher.launch(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment