Listen incoming calls through BroadcastReceiver, without PhoneStateIntentReceiver or PhoneStateListener

后端 未结 2 1182
面向向阳花
面向向阳花 2021-01-31 23:41

Is there any way to listen to incoming calls by extending BroadcastReceiver to listen to OS\'s broadcast,without using PhoneStateIntentReceiver or PhoneStateListener. Also pleas

2条回答
  •  独厮守ぢ
    2021-02-01 00:10

    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

    
    
    

提交回复
热议问题