Filter Intent based on custom data

别等时光非礼了梦想. 提交于 2019-12-21 11:38:35


I want to broadcast intent with custom-data and only the receiver that have this custom data should receive this intent, how this could be done ?

this how i broadcast the intent :

Intent intent = new Intent();

and i define the broadcast receiver as following :

 <receiver android:name="com.test.myReceiver" android:enabled="true">
            <action android:name="com.example"></action>


Setup your myReceiver class basically how anmustangs posted.

public class myReceiver extends BroadcastReceiver{

    public void onReceive(Context arg0, Intent intent) {
        //Do something

You shouldn't have to check the Intent action because you've already filtered for it based on what you've included in your manifest, at least in this simple case. You could have other actions and filters in which case you'd need to have some kind of check on the received intent.

If you want the filter to filter on data, the sdk documentation on intent filters covers that. I'm not great with data types so any example I would give would be relatively poor. In any event, here is a link to the manifest intent filter page:

And the specific page for the data element;


If you already define your broadcast receiver class, then the next step is to register it on the Activity/Service which you'd like to receive the broadcast intent. An example to register:

    IntentFilter iFilter = new IntentFilter();
    iFilter.addAction("com.example"); //add your custom intent to register
    //below is your class which extends BroadcastReceiver, contains action 
    //which will be triggered when current class received the broadcast intent
    MyReceiver myReceiver = new MyReceiver(); 
    registerReceiver(myReceiver, iFilter); //register intent & receiver

If you destroy the activity/service, for best practice don't forget to unregister the broadcast receiver on the same activity/service:

protected void onDestroy() {

MyReceiver class:

public class MyReceiver extends BroadcastReceiver{

    public void onReceive(Context arg0, Intent intent) {
            //DO SOMETHING HERE