Skip to content

Instantly share code, notes, and snippets.

@alorma
Last active Jul 22, 2021
Embed
What would you like to do?
private fun launchIntents(context: Context) {
val whatsappIntent = getWhatsappIntent(context)
val telegramIntent = getTelegramIntent(context)
val intents = listOfNotNull(whatsappIntent, telegramIntent)
val globalIntent = Intent()
val chooserIntent = Intent.createChooser(globalIntent, "Send message")
.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents.toTypedArray())
startActivity(chooserIntent)
}
private fun getWhatsappIntent(context: Context): Intent? = getAppIntent(
context,
"com.whatsapp",
"Whatsapp message"
)
private fun getTelegramIntent(context: Context): Intent? = getAppIntent(
context,
"org.telegram.messenger",
"Telegram message"
)
private fun getAppIntent(context: Context, packageName: String, text: String): Intent? {
val pm: PackageManager = context.packageManager
return try {
val intent = Intent(Intent.ACTION_SEND)
intent.type = "text/plain"
pm.getPackageInfo(
packageName,
PackageManager.GET_META_DATA
)
//Check if package exists or not. If not then code
//in catch block will be called
intent.setPackage(packageName)
intent.putExtra(Intent.EXTRA_TEXT, text)
intent
} catch (e: PackageManager.NameNotFoundException) {
null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment