intent.action.PHONE_STATE broadcast receiver not working when app closed

2.6k views Asked by At

i am trying to detect incoming calls by using this broadcast

   <receiver android:name=".IncomingCallReceiver"
                android:enabled="true"
    
                android:exported="true">
                <intent-filter android:priority="2147483647">
                    <action android:name="android.intent.action.PHONE_STATE" />
                </intent-filter  >
                <intent-filter android:priority="2147483647">
                    <action android:name="android.intent.action.NEW_OUTGOING_CALL" />
                </intent-filter>
            </receiver>

and this is java code

public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL")) {
//            savedNumber = intent.getExtras().getString("android.intent.extra.PHONE_NUMBER");
        }
        else{
            String stateStr = intent.getExtras().getString(TelephonyManager.EXTRA_STATE);
            String number = intent.getExtras().getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
            int state = 0;
            if(stateStr.equals(TelephonyManager.EXTRA_STATE_IDLE)){
                state = TelephonyManager.CALL_STATE_IDLE;
            }
            else if(stateStr.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)){
                state = TelephonyManager.CALL_STATE_OFFHOOK;
            }
            else if(stateStr.equals(TelephonyManager.EXTRA_STATE_RINGING)){
                state = TelephonyManager.CALL_STATE_RINGING;
            }


            onMyCallStateChanged(context, state, number);
        }


//            TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
//            telephony.listen(new PhoneStateListener() {
//                @Override
//                public void onCallStateChanged(int state, String phoneNumber) {
//
//                    onMyCallStateChanged(context, state, phoneNumber);
//                }
//            }, PhoneStateListener.LISTEN_CALL_STATE);
        }

the issue is when app get closed or removed from recent this broadcast not working. in android docs, it is mentioned that this will work in the background

1

There are 1 answers

1
Rishabh Ritweek On

Make sure that you have this in the manifest.

 <uses-permission android:name="android.permission.READ_PHONE_STATE" />
 <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>

if not, the broadcast receiver will silently fail.