Jay Panchal
Jay Panchal

Reputation: 304

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

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?

Any suggestions or workarounds would be greatly appreciated! ๐Ÿš€

Upvotes: 0

Views: 43

Answers (0)

Related Questions