In android, Broadcast Receiver is a component which will allow android system or other apps to deliver events to the app like sending a low battery message or screen turned off message to the app. The apps can also initiate broadcasts to let other apps know that required data available in a device to use it.
Generally, we use Intents to deliver broadcast events to other apps and Broadcast Receivers use status bar notifications to let user know that broadcast event occurs.
In android, Broadcast Receiver is implemented as a subclass of BroadcastReceiver and each broadcast is delivered as an Intent object.
We can register an app to receive only few broadcast messages based on our requirements. When a new broadcast received, the system will check for specified broadcasts have subscribed or not based on that it will routes the broadcasts to the apps.
Receiving Broadcasts
In android, we can receive broadcasts by registering in two ways.
One way is by registering a broadcasts using android application manifest file (AndroidManifest.xml). We need to specify <receiver> element in apps manifest file like as shown below.
<receiver android:name=".SampleBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
The above statement will fire the defined system broadcast event whenever the boot process is completed.
Another way is to register a receiver dynamically via Context.registerReceiver() method. To register broadcast receiver we need to extend our class using BroadcastReceiver and need to implement a onReceive(Context, Intent) method like as shown below.
public class MainActivity extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, log, Toast.LENGTH_LONG).show();
}
}
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, log, Toast.LENGTH_LONG).show();
}
}
Suppose if we register for ACTION_BOOT_COMPLETED event, whenever the boot process is completed the broadcast receiver’s method onReceive() method will be invoked.
Sending Broadcasts
In android, we can send a broadcasts in apps using three different ways, those are
Method | Description |
---|---|
sendOrderedBroadcast(Intent, String) | This method is used to send broadcasts to one receiver at a time. |
sendBroadcast(Intent) | This method is used to send broadcasts to all receivers in an undefined order. |
LoadBroadcastManager.sendBroadcast | This method is used to send broadcasts to receivers that are in the same app as the sender. |
Broadcasting Custom Intents
In android we can create our own custom broadcasts using intents. Following is the simple code snippet of sending a broadcast by creating an intent using sendBroadcast(Intent) method.
Intent sintent = new Intent();
intent.setAction("com.tutlane.broadcast.MY_NOTIFICATION");
intent.putExtra("data","Welcome to Tutlane");
sendBroadcast(intent);
intent.setAction("com.tutlane.broadcast.MY_NOTIFICATION");
intent.putExtra("data","Welcome to Tutlane");
sendBroadcast(intent);
If you observe above code snippet we create a custom Intent “sintent”. We need to register our intent action in android manifest file like as shown below
<receiver android:name=".SampleBroadcastReceiver">
<intent-filter>
<action android:name=" com.tutlane.broadcast.MY_NOTIFICATION"/>
</intent-filter>
</receiver>
<action android:name=" com.tutlane.broadcast.MY_NOTIFICATION"/>
</intent-filter>
</receiver>
This is how we can create our own custom broadcasts using Intents in android applications.
System Broadcasts
In android, several system events are defined as final static fields in the Intent class. Following are the some of system events available in android applications.
Event | Description |
---|---|
android.intent.action.BOOT_COMPLETED | It raise an event, once boot completed. |
android.intent.action.POWER_CONNECTED | It is used to trigger an event when power connected to the device. |
android.intent.action.POWER_DISCONNECTED | It is used to trigger an event when power got disconnected from the device. |
android.intent.action.BATTERY_LOW | It is used to call an event when battery is low on device. |
android.intent.action.BATTERY_OKAY | It is used to call an event when battery is OKAY again. |
android.intent.action.REBOOT | It call an event when the device rebooted again. |
Likewise we have many system events available in android application.
Android BroadcastReceiver Example
To setup a Broadcast Receiver in our android application we need to do following things.
- Create a BroadcastReceiver
- Register a BroadcastReceiver
Create a new android application using android studio and give names as BroadcastReceiver. In case if you are not aware of creating an app in android studio check this article Android Hello World App.
Now we need to create our own broadcast content file MyBroadcastReceiver.java in \src\main\java\com.tutlane.broadcastreceiver path to define our actual provider and associated methods for that right click on your application folder à Go to New à select Java Class and give name as MyBroadcastReceiver.java.
Once we create a new file MyBroadcastReceiver.java, open it and write the code like as shown below
MyBroadcastReceiver.java
package com.tutlane.broadcastreceiver;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.widget.Toast;/**
* Created by Tutlane on 01-08-2017.
*/public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent){
CharSequence iData = intent.getCharSequenceExtra("msg");
Toast.makeText(context,"Tutlane Received Message: "+iData,Toast.LENGTH_LONG).show();
}
}
* Created by Tutlane on 01-08-2017.
*/public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent){
CharSequence iData = intent.getCharSequenceExtra("msg");
Toast.makeText(context,"Tutlane Received Message: "+iData,Toast.LENGTH_LONG).show();
}
}
Now open activity_main.xml file from \src\main\res\layout path and write the following code.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/txtMsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="180dp"
android:ems="10"/>
<Button
android:id="@+id/btnShow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClickShowBroadcast"
android:layout_marginLeft="130dp"
android:text="Show Broadcast"/>
</LinearLayout>
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/txtMsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="180dp"
android:ems="10"/>
<Button
android:id="@+id/btnShow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClickShowBroadcast"
android:layout_marginLeft="130dp"
android:text="Show Broadcast"/>
</LinearLayout>
Now open MainActivity.java file from \java\com.tutlane.broadcastreceiver path and write following to implement custom broadcast intents.
MainActivity.java
package com.tutlane.broadcastreceiver;import android.content.Intent;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.EditText;public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClickShowBroadcast(View view){
EditText st = (EditText)findViewById(R.id.txtMsg);
Intent intent = new Intent();
intent.putExtra("msg",(CharSequence)st.getText().toString());
intent.setAction("com.tutlane.CUSTOM_INTENT");
sendBroadcast(intent);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClickShowBroadcast(View view){
EditText st = (EditText)findViewById(R.id.txtMsg);
Intent intent = new Intent();
intent.putExtra("msg",(CharSequence)st.getText().toString());
intent.setAction("com.tutlane.CUSTOM_INTENT");
sendBroadcast(intent);
}
}
Now we need to register our broadcast receiver in android manifest file (AndroidManifest.xml) using <receiver> attribute like as shown below.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tutlane.broadcastreceiver">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="MyBroadcastReceiver">
<intent-filter>
<action android:name="com.tutlane.CUSTOM_INTENT">
</action>
</intent-filter>
</receiver>
</application>
</manifest>
package="com.tutlane.broadcastreceiver">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="MyBroadcastReceiver">
<intent-filter>
<action android:name="com.tutlane.CUSTOM_INTENT">
</action>
</intent-filter>
</receiver>
</application>
</manifest>
Output of Android BroadcastReceiver Example
When we run above example in android emulator we will get a result like as shown below
This is how we can use broadcast receivers in our android applications to send broadcast messages to apps based on our requirements.
No comments:
Post a Comment