Broadcast Receiver in Android
Hello friends hi. This post is regarding all about Broadcast Receiver in Android. Broadcast Receiver is one of the four main component of Android application. So let's start...
Broadcast Receivers can send or receive messages from other application or from the system itself. These messages can be an event or an Intent.
For example:- Android system sends broadcasts when system events occur such as system boots up, device starts charging low battery.
Furthermore, apps can send custom broadcasts to notify other apps(data download completed).
Apps can receive broadcasts in two ways:
a)- Manifest-declared receivers(Statically)
b)- Context-registered receivers(Dynamically)
a)- Manifest-declared receivers(Statically):-
The registration is done in the manifest file, using <register> tags.
Firstly, specify the receiver in your manifest file.
<receiver android:name=".MyBroadcastReceiver" android:exported="true">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE""/>
</intent-filter>
</receiver>
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE""/>
</intent-filter>
</receiver>
Secondly, create class as a subclass of BroadcastReceiver class and overriding the onReceive() method where each message is received as a Intent object parameter.
public class MyBroadcastReceiver extends BroadcastReceiver { @Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
}
}
b)- Context-registered receivers(Dynamically):-
The registration is done using Context.registerReceiver() method.
Firstly, register broadcast receiver programmatically.
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(getPackageName() + "android.net.conn.CONNECTIVITY_CHANGE");
intentFilter.addAction(getPackageName() + "android.net.conn.CONNECTIVITY_CHANGE");
MyBroadcastReceiver myReceiver = new MyBroadcastReceiver();
registerReceiver(myReceiver, filter);
@Override protected void onPause() {
unregisterReceiver(myReceiver);
super.onPause();
unregisterReceiver(myReceiver);
super.onPause();
}
---Sending broadcasts---
There are three distinctive way to send broadcast:
1- The sendOrderedBroadcast(Intent, String) method sends broadcasts to one receiver at a time.
2-The sendBroadcast(Intent) method sends broadcasts to all receivers in an undefined order.
3-The LocalBroadcastManager.sendBroadcast method sends broadcasts to receivers that are in the same app as the sender.
Intent intent = new Intent();
intent.setAction("com.example.broadcast.MY_NOTIFICATION");
intent.putExtra("data", "Nothing to see here, move along.");
sendBroadcast(intent);//With permissions
sendBroadcast(new Intent("com.example.NOTIFY"),
Manifest.permission.SEND_SMS);//the receiving app must request the permission
<uses-permission android:name="android.permission.SEND_SMS"/>

Comments
Post a Comment