Search code examples
androidandroid-intentbroadcastreceiver

How to get the name or type of the Intent fired from onReceive()


I need to create a BroadcastReceiver that listens for when the the phone receives or makes a call, so I can take note of when it started and when it ended. I realized that the two receivers will look almost the same so instead of creating two separate BroadcastReceivers for incoming and for outgoing calls, I can just create one for both and make my actions depend on what event was fired.

I registered intent-filters for android.intent.action.PHONE_STATE and android.intent.action.NEW_OUTGOING_CALL in the manifest, but how do I find out from onReceive() what kind of Intent was fired?

@Override
public void onReceive(Context context, Intent intent) {
    Bundle extras = intent.getExtras();

    // get the intent fired--incoming or outgoing call?
    // then, save it in a variable and perform corresponding actions
}

Solution

  • just use intent.getAction();

    String action=intent.getAction();
    
    if(action.equalsIgnoreCase(Intent.ACTION_NEW_OUTGOING_CALL)){
    
    //dosomething here
    }
    else if(action.equalsIgnoreCase(second action)){
    
    //do something here
    }