Skip to content

Instantly share code, notes, and snippets.

@mksantoki
Created September 16, 2020 17:12
Show Gist options
  • Save mksantoki/efb0fcda37012ce5b0af10417502fc32 to your computer and use it in GitHub Desktop.
Save mksantoki/efb0fcda37012ce5b0af10417502fc32 to your computer and use it in GitHub Desktop.
This extensions is used to perform intent operations
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 */
)
}
@mksantoki
Copy link
Author

This extensions are used to pick image from gallery,camera and pick document from phone file manager

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment