Last active
July 22, 2021 08:18
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
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