Search code examples
androidbroadcastreceivertelephonymanagerandroid-broadcastreceiverphone-state-listener

addAction to IntentFilter to handle Phone State Change


I want to listen to an incoming call.

I know that you have to give permissions inside AndroidManifest and set the receiver with

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

and

<receiver ... 
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />...


But, in my project, I have the receiver set by code, with

IntentFilter filter = new IntentFilter();
filter.addAction( ... );
registerReceiver(broadcastReceiver, filter);

Where inside addAction I put TelephonyManager.ACTION_PHONE_STATE_CHANGED
and I create the BroadcastReceiver with

private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) { ...

Then, inside it, I take the action from the intent with String action = intent.getAction(); and I check which action is it.

It works great for Bluetooth

filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);

And

switch (action) {
    case BluetoothAdapter.ACTION_DISCOVERY_STARTED: ...

But it does not checks TelephonyManager.ACTION_PHONE_STATE_CHANGED.

So, my questions are:
How do you set the action (addAction()) to listen to state changes?
Is TelephonyManager.ACTION_PHONE_STATE_CHANGED not right?
If I would give up and set the receiver inside AndroiManifest, how would I set the filters for Bluetooth? I'm using

BluetoothDevice.ACTION_FOUND
BluetoothAdapter.ACTION_DISCOVERY_STARTED
BluetoothAdapter.ACTION_DISCOVERY_FINISHED

Solution

  • First register reciever in your activity

    this.registerReceiver(this.broadcastReceiver, new IntentFilter(TelephonyManager.ACTION_PHONE_STATE_CHANGED));
    

    and this is the broadcastReceiver:

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    
        @Override
        public void onReceive(Context context, Intent intent) {
            String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
    
            if (state == null) {
    
                //Outgoing call
                String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
                Log.e("tag", "Outgoing number : " + number);
    
            } else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
    
                Log.e("tag", "EXTRA_STATE_OFFHOOK");
    
            } else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
    
                Log.e("tag", "EXTRA_STATE_IDLE");
    
            } else if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
    
                //Incoming call
                String number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
                Log.e("tag", "Incoming number : " + number);
    
            } else
                Log.e("tag", "none");
        }
    };