BroadCast Receiver with Custom Intent.
Intent intent=new Intent();
intent.setAction(CUSTOM_INTENT);//should be as package name
BroadcastReceiver receiver=new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
}
};
IntentFilter filter=new IntentFilter("Custom_Intent");
registerReceiver(receiver, filter);
sendBroadcast(intent);
BroadCast Receiver with System Events.
Step 1:
Add receiver to Android Manifest File:
<receiver android:name=".PhoneReceiver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
Step 2: Define your Broad cast Receiver
public class PhoneReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//toDo
}
}
Important Points:
- Broadcast receiver should complete its onReceive() Method with in 5 sec.
- Difference between sendStickyBroadcast() and sendBroadcast() is:
Perform a sendBroadcast(Intent) that is "sticky," meaning the Intent you are sending stays around after the broadcast is complete, so that others can quickly retrieve that data through the return value of registerReceiver(BroadcastReceiver, IntentFilter). In all other ways, this behaves the same as sendBroadcast(Intent).
One example of a sticky broadcast sent via the operating system is
ACTION_BATTERY_CHANGED
. When you call registerReceiver()
for that action -- even with a null
BroadcastReceiver
-- you get the Intent
that was last broadcast for that action. Hence, you can use this to find the state of the battery without necessarily registering for all future state changes in the battery.- android:pirority can be used to control broadcast intents between receiver if it was an ordered Broadcast.