Skip to content

Instantly share code, notes, and snippets.

@grishko188
Created January 25, 2023 17:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grishko188/d927e0a9688f79f1e514e96d5f70ae46 to your computer and use it in GitHub Desktop.
Save grishko188/d927e0a9688f79f1e514e96d5f70ae46 to your computer and use it in GitHub Desktop.
Fetching shared data from intent
fun Intent.parseSharedContent(): SharedContent {
if (action != Intent.ACTION_SEND) return SharedContent(null, ContentType.EMPTY)
return if (isTextMimeType()) {
val textContent = getStringExtra(Intent.EXTRA_TEXT) ?: ""
if (Patterns.WEB_URL.matcher(textContent).matches()) {
SharedContent(textContent, ContentType.URL)
} else {
SharedContent(textContent, ContentType.PLAIN_TEXT)
}
} else if (isImageMimeType()) {
val imageContent = getParcelableExtra<Parcelable>(Intent.EXTRA_STREAM) as? Uri
if (imageContent != null) {
SharedContent(imageContent.toString(), ContentType.LOCAL_IMAGE)
} else {
SharedContent.EMPTY
}
} else {
SharedContent.EMPTY
}
}
private fun Intent.isTextMimeType() = type?.startsWith(MIME_TYPE_TEXT) == true
private fun Intent.isImageMimeType() = type?.startsWith(MIME_TYPE_IMAGE) == true
private const val MIME_TYPE_TEXT = "text/"
private const val MIME_TYPE_IMAGE = "image/"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment