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();
 intent.setAction("com.example");
 context.sendBroadcast(intent);

and i define the broadcast receiver as following :

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

回答1:


Setup your myReceiver class basically how anmustangs posted.

public class myReceiver extends BroadcastReceiver{

    @Override
    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: http://developer.android.com/guide/topics/manifest/intent-filter-element.html

And the specific page for the data element; http://developer.android.com/guide/topics/manifest/data-element.html




回答2:


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:

@Override
protected void onDestroy() {
    if(myReceiver!=null)
        unregisterReceiver(myReceiver)
    super.onDestroy();
}

MyReceiver class:

public class MyReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context arg0, Intent intent) {
        if(intent.getAction().equals("com.example")){
            //DO SOMETHING HERE
        }
    }
}


来源:https://stackoverflow.com/questions/5957519/filter-intent-based-on-custom-data

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