最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to detect phone calls when the app is killed without using Foreground Service in Android? - Stack Overflow

programmeradmin1浏览0评论

Problem Statement

I am developing an Android app that needs to detect incoming and outgoing phone calls, even when the app is killed. I have implemented a BroadcastReceiver (CallReceiver) to listen for TelephonyManager.ACTION_PHONE_STATE_CHANGED, and it works fine when the app is running in the background.

However, the issue occurs when the app is force-stopped or killed—the BroadcastReceiver no longer receives phone call events. I want to detect phone calls without relying on a Foreground Service with a persistent notification.

What I Have Tried

  1. Using a BroadcastReceiver

    • Implemented a CallReceiver to listen for TelephonyManager.ACTION_PHONE_STATE_CHANGED.
    • Works when the app is in the background but stops working when the app is killed.
  2. Using WorkManager

    • Implemented a Worker that registers the CallReceiver.
    • Does not work when the app is killed because WorkManager is not designed for real-time broadcast listening.
  3. Using a Foreground Service (Works, but not ideal)

    • Created a CallMonitoringService that registers the receiver dynamically.
    • Works even when the app is killed, but requires a persistent notification, which I want to avoid.
  4. Using a Bound Service

    • A Bound Service stops when the app is killed, so it does not solve the problem.

Code Implementation

BroadcastReceiver (CallReceiver)

class CallReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        if (context == null || intent?.action != TelephonyManager.ACTION_PHONE_STATE_CHANGED) return

        val state = intent.getStringExtra(TelephonyManager.EXTRA_STATE)
        val incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER)

        when (state) {
            TelephonyManager.EXTRA_STATE_RINGING -> {
                Log.d("CallReceiver", "Incoming call from: $incomingNumber")
            }
            TelephonyManager.EXTRA_STATE_OFFHOOK -> {
                Log.d("CallReceiver", "Call answered or dialed!")
            }
            TelephonyManager.EXTRA_STATE_IDLE -> {
                Log.d("CallReceiver", "Call ended!")
            }
        }
    }
}

❓ How can I detect phone calls even when the app is killed, without using a Foreground Service with a persistent notification?

  • Is there a way to restart my CallReceiver when the app is killed?
  • Can JobScheduler or BroadcastReceiver be used differently to achieve this?
  • What is the best approach to achieve call detection without relying on a foreground notification?

Any suggestions or workarounds would be greatly appreciated!

发布评论

评论列表(0)

  1. 暂无评论