androidbroadcastreceiverphone-call

How to detect incoming call phone number in Android when app is killed?


I want to detect incoming/outgoing call phone numbers when my app is not running, it is killed. I have implemented the following code by it only detects call if the app is running or in the background but not working when the app is killed.

public class CallReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

    if(intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_OFFHOOK)){
        String outgoingPhoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
        showToast(context,"Call Outgoing to "+outgoingPhoneNumber);
    }else if(intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_IDLE)){
        String callEndedNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
        showToast(context,"Call Ended to "+callEndedNumber);
    }else if(intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_RINGING)){
        String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
        showToast(context, "Incoming call from "+ incomingNumber);
    }
}

private void  showToast(Context context, String message){

    Toast.makeText(context, message, Toast.LENGTH_SHORT).show();

}

}

Manifests

  <receiver android:name=".CallReceiver"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.PHONE_STATE"/>
        </intent-filter>
    </receiver>

Solution

  • Not exactly an answer, but you can create your custom calling app and then make it default by asking for permission. A demo app can be found on this repository. Look at this app code and you might get it.