Created
September 16, 2020 17:12
-
-
Save mksantoki/efb0fcda37012ce5b0af10417502fc32 to your computer and use it in GitHub Desktop.
This extensions is used to perform intent operations
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
fun onDocument(): Intent { | |
val mimeTypes = arrayOf( | |
"application/pdf", | |
"image/*" | |
) | |
val intent = Intent(Intent.ACTION_GET_CONTENT) | |
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); | |
intent.addCategory(Intent.CATEGORY_OPENABLE) | |
intent.type = if (mimeTypes.size == 1) mimeTypes[0] else "*/*" | |
if (mimeTypes.isNotEmpty()) { | |
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes) | |
} | |
return intent | |
} | |
fun onGallery(): Intent { | |
val intent = Intent(Intent.ACTION_PICK) | |
intent.type = "image/*" | |
val mimeTypes = | |
arrayOf("image/jpeg", "image/png") | |
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes) | |
return intent | |
} | |
fun View.captureFromCamera(): Intent? { | |
Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent -> | |
takePictureIntent.resolveActivity(context.packageManager)?.also { | |
val photoFile: File? = try { | |
createImageFile(context) | |
} catch (ex: IOException) { | |
// Error occurred while creating the File | |
return null | |
} | |
if (photoFile != null) { | |
this.tag = photoFile.absolutePath | |
} | |
photoFile?.also { | |
val photoURI: Uri = FileProvider.getUriForFile( | |
context, | |
"${BuildConfig.APPLICATION_ID}.provider", | |
it | |
) | |
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI) | |
return takePictureIntent | |
} | |
} | |
} | |
return null | |
} | |
@Throws(IOException::class) | |
private fun createImageFile(context: Context): File { | |
val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date()) | |
val storageDir: File? = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES) | |
return File.createTempFile( | |
"JPEG_${timeStamp}_", /* prefix */ | |
".jpg", /* suffix */ | |
storageDir /* directory */ | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This extensions are used to pick image from gallery,camera and pick document from phone file manager