I'm trying to develop an app that:
- Listens to push notifications
- If the push notification is from WhatsApp + contains certain info, the app should call a specific number.
- For the sake of the argument, let's assume that both permissions (call + notification listener) have already been granted.
So I used the below code (and of course, added the listener to the manifest), which works while the app is in the front, but not when it's in the background or closed. I also tried replacing "startActivity" with "startService", but that didn't work either. What's the correct way to leave the service running in the background and actually calling a number even though the app is in the background or closed? Also, is there a certain way to achieve this even the phone is locked?
class NotificationListener : NotificationListenerService() {
companion object {
private const val TAG = "NotificationListener"
private const val WA_PACKAGE = "com.whatsapp"
}
override fun onListenerConnected() {
Log.i(TAG, "Notification Listener connected")
Toast.makeText(applicationContext, "Notification Listener connected", Toast.LENGTH_SHORT).show()
}
override fun onNotificationPosted(sbn: StatusBarNotification) {
if (sbn.packageName != WA_PACKAGE) {
return
}
val notification = sbn.notification
val extras: Bundle = notification.extras
val from = extras.getString(NotificationCompat.EXTRA_TITLE)
val message = extras.getString(NotificationCompat.EXTRA_TEXT)
if (from != null && from.contains("test") && message != null && message.contains("gate")) {
val msg = "[$from]\n[$message]"
Log.i(TAG, msg)
Toast.makeText(applicationContext, msg, Toast.LENGTH_SHORT).show()
attemptCallGate()
}
}
private fun attemptCallGate() {
when (ContextCompat.checkSelfPermission(applicationContext, Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
true -> callGate()
false -> Toast.makeText(applicationContext, R.string.access_denied, Toast.LENGTH_SHORT).show()
}
}
private fun callGate() {
val number = "1234567890"
try {
val callIntent = Intent(Intent.ACTION_CALL, Uri.parse("tel:$number"))
callIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
Toast.makeText(applicationContext, "Attempting to call [$number]", Toast.LENGTH_SHORT).show()
startActivity(callIntent)
} catch (e: Exception) {
Toast.makeText(applicationContext, "Failed calling [$number] ${e.message}", Toast.LENGTH_SHORT).show()
}
}
}