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>
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
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
}
}
}