应用程序在后台时拨打电话号码

时间:2021-08-01 12:30:53

标签: android kotlin android-intent notification-listener

我正在尝试开发一个应用:

  1. 收听推送通知
  2. 如果推送通知来自 WhatsApp + 包含某些信息,应用程序应拨打特定号码。
  3. 为了论证起见,我们假设两个权限(调用 + 通知侦听器)都已被授予。

所以我使用了下面的代码(当然,将侦听器添加到清单中),它在应用程序在前面时有效,但在后台或关闭时无效。我也尝试用“startService”替换“startActivity”,但这也不起作用。即使应用程序在后台或关闭,让服务在后台运行并实际拨打号码的正确方法是什么?另外,有没有什么办法可以在手机被锁的情况下做到这一点?

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()
    }
}

}

0 个答案:

没有答案