Listen incoming calls through BroadcastReceiver, without PhoneStateIntentReceiver or PhoneStateListener

99封情书 提交于 2019-12-02 17:47:13

The action you have defined in your manifest is incorrect. this is an Action Intent that can be used to answer a call and not monitor incoming calls.

You can use two broadcast receivers that listen to ACTION_PHONE_STATE_CHANGED and NEW_OUTGOING_CALL broadcast intents.

The ACTION_PHONE_STATE_CHANGED will be received when there is a new incoming call, call answered or hangup (See the documentation for the EXTRAs received with this Intent).

The NEW_OUTGOING_CALL will be received when there is a new outgoing call placed on your device.

As for permissions, I think you got it about right in your manifest (I assume the RECORD_AUDIO permission is used for something else in your application)

Here is My demo for android unit test. You can refer to it.

public interface ICallVerify {
    void onOutgoing(Context context, Intent intent);
    void onCallStateChange(Context context, Intent intent);
}

protected void setUpCallVerify(final ICallVerify callVerify) {  //listen ingoing and outgoing
    final CountDownLatch latch = new CountDownLatch(1);
    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) { //state change
                Log.i(TAG, "outgoing call...");
                callVerify.onOutgoing(context, intent);
            } else if (intent.getAction().equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)){ // state changed
                String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
                if (state.equals("RINGING")) {
                    state += " number:" + intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
                }
                Log.i(TAG, "call state changed.... " + state);
                callVerify.onCallStateChange(context, intent);
            }
        }
    };

    IntentFilter filter = new IntentFilter(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
    filter.addAction(Intent.ACTION_NEW_OUTGOING_CALL);
    ContextUtils.getTargetContext().registerReceiver(receiver, filter);

    try {
        latch.await(5, TimeUnit.MINUTES);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

Dont forget to add permissions

<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"></uses-permission>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!