Broadcast Receiver - To listen the system as well as custom intent.
Android OS is firing multiple intents like - SYSTEM_REBOOT, BATTERY_LOW/HIGH, NETWORK STATUS and so on.
Intent - It is a messaging object which is used to pass the message from one component to another.
1. Create BroadcastReceiver Class
public class BReceiver extends BroadcastReceiver
2. Register and Filter Intent - Register Broadcast Receiver class to listen to System intent.
and by using IntentFilter we specify which intent app listens.
2.1 Register receiver in Android Manifest
<receiver android:name=".BReceiver"> <intent-filter> <action android:name="divakar"></action> </intent-filter> </receiver>
2.2 Register receiver programmatically.
final BReceiver bReceiver = new BReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction("divakar"); registerReceiver(bReceiver, filter);
if you want to send broadcast localy(within app)
LocalBroadcastManager.getInstance(this).registerReceiver(bReceiver, filter);
3. Receive data
@Override public void onReceive(Context context, Intent intent) { if (intent.getAction() == Manifest.permission.CHANGE_WIFI_STATE) { } }
4. Send Custom Intent
Intent i = new Intent(); i.setAction("divakar"); i.putExtra("key", "divakar-main-data"); sendBroadcast(i, Manifest.permission.CHANGE_WIFI_STATE);
5. Receive Custom Intent
@Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equalsIgnoreCase("divakar")) { String s = intent.getExtras().getString("key"); Toast.makeText(context, "Broadcast Receiver called : "+s, Toast.LENGTH_LONG).show(); }else { Toast.makeText(context, "Something changed", Toast.LENGTH_LONG).show(); } }
No comments:
Post a Comment