- First of all define all the permission you want on compile time permission like in manifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.CAMERA" />
- Now , in activity file
private lateinit var pickImageLauncher: ActivityResultLauncher<Intent>
private lateinit var requestPermissionLauncher: ActivityResultLauncher<String>
After onCreate() create & call registerPermissionLauncher().
this function contains
private fun registerPermissionLauncher() {
requestPermissionLauncher = registerForActivityResult(
ActivityResultContracts.RequestPermission()
) { isGranted ->
if (isGranted) {
// Permission is granted
openGallery()
} else {
val intent = Intent().apply {
action = android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS
data = Uri.fromParts("package", requireActivity().packageName, null)
}
requireActivity().startActivity(intent)
}
}
}- you have to create function for check permission & call wherever you want.
private fun permissionCheck() {
val permission =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) android.Manifest.permission.READ_MEDIA_IMAGES
else android.Manifest.permission.READ_EXTERNAL_STORAGE
if (ContextCompat.checkSelfPermission(
requireContext(), permission
) != PackageManager.PERMISSION_GRANTED
) {
requestPermissionLauncher.launch(permission)
} else {
dialogShow(DialogAddproductBinding.inflate(layoutInflater))
}
} also create and call at onCreate function pickImageResult() which contains
it will handle the data as you want.private fun pickImageResult() {
pickImageLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
result.data?.data?.let { imageUri ->
lifecycleScope.launch {
val imageBitmap = withContext(Dispatchers.IO) {
context?.contentResolver?.openInputStream(imageUri)
?.use { inputStream ->
BitmapFactory.decodeStream(inputStream)
}
}
val resizedBitmap = resizeImage(imageBitmap!!)
picURI = saveImageToInternalStorage(resizedBitmap)
dialBinding?.productImageView?.setImageBitmap(resizedBitmap)
}
}
}
}
}
0 Comments