Skip to content

Instantly share code, notes, and snippets.

@Elblassy
Created November 27, 2020 12:46
Show Gist options
  • Save Elblassy/1cccd70d13dc55e375ea4a8bef52eb7f to your computer and use it in GitHub Desktop.
Save Elblassy/1cccd70d13dc55e375ea4a8bef52eb7f to your computer and use it in GitHub Desktop.
private fun openWhatsApp(fileName: String) {
val smsNumber = mobileNumber
val isWhatsappInstalled = "com.whatsapp".whatsappInstalledOrNot()
if (isWhatsappInstalled) {
val sendIntent = Intent(Intent.ACTION_SEND)
val outputFile = File(
requireContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS),
fileName
)
Log.e(TAG, "openWhatsApp: $outputFile")
Log.e(TAG, "openWhatsApp: ${outputFile.absolutePath}")
val fileUri: Uri = FileProvider.getUriForFile(
requireActivity().applicationContext,
"${requireActivity().applicationContext.packageName}.provider", outputFile
)
sendIntent.putExtra(
"jid",
PhoneNumberUtils.stripSeparators(smsNumber) + "@s.whatsapp.net"
) //phone number without "+" prefix
sendIntent.setPackage("com.whatsapp")
sendIntent.action = Intent.ACTION_SEND
sendIntent.type = "application/pdf"
sendIntent.putExtra(Intent.EXTRA_STREAM, fileUri)
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP) {
sendIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION)
} else {
sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
startActivityForResult(sendIntent, whatsAppCode)
} else {
val uri: Uri = Uri.parse("market://details?id=com.whatsapp")
val goToMarket = Intent(Intent.ACTION_VIEW, uri)
Toasty.error(
requireContext(), "WhatsApp not Installed",
Toast.LENGTH_LONG,
true
).show()
startActivity(goToMarket)
}
}
private fun String.whatsappInstalledOrNot(): Boolean {
val pm: PackageManager = requireActivity().packageManager
var appInstalled = false
appInstalled = try {
pm.getPackageInfo(this, PackageManager.GET_ACTIVITIES)
true
} catch (e: PackageManager.NameNotFoundException) {
false
}
return appInstalled
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment