Android Broadcast Receivers

 

Android Broadcast Receivers

Android Broadcast Receivers just react to broadcast messages from different applications or from the framework itself. These messages are at some point called events or intent. For instance, applications can likewise start broadcast to tell different applications that a few information has been downloaded to the device and is accessible for them to utilize, so this is an android broadcast receivers who will capture this correspondence and will start the proper activity.

android broadcast receivers

There are two main steps to create Android Broadcast Receiver which works the system broadcasted intents.Steps are following below

  • Creating The Android Broadcast Receivers
  • Registering Android  Broadcast Receivers

There is one extra step in the event that you are going to execute your custom intents then you will need to make and broadcast those intents.

Creating the Android Broadcast Receivers

An android broadcast receiver is actualized as a subclass of BroadcastReceiver class and overriding the onReceive() strategy where every message is gotten as an Intent object parameter.

public class MyReceiver extends BroadcastReceiver {
   @Override
   public void onReceive(Context context, Intent intent) {
      Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
   }
}

 


Registering Android Broadcast Receivers

 

An application listens for particular broadcast intents by registering a broadcast receiver in AndroidManifest.xml file. Consider we are going to register MyReceiver for framework created event ACTION_BOOT_COMPLETED which is terminated by the framework once the Android framework has finished the boot procedure.

android broadcast receivers

<application
   android:icon="@drawable/ic_launcher"
   android:label="@string/app_name"
   android:theme="@style/AppTheme" >
   <receiver android:name="MyReceiver">
   
      <intent-filter>
         <action android:name="android.intent.action.BOOT_COMPLETED">
         </action>
      </intent-filter>
   
   </receiver>
</application>

 

Presently at whatever point your Android device gets booted, it will be blocked by BroadcastReceiver MyReceiver and actualized loginc inside onReceive() will be executed.

There are a few system created events characterized as definite static fields in the Intent class. The Following tables contains important system events.

Event Constant                                                     Description

android.intent.action.BATTERY_CHANGED  – Sticky broadcast containing the charging state, level, and other data about the battery.

android.intent.action.BATTERY_LOW – Indicates low battery condition on the device.

android.intent.action.BATTERY_OKAY  –  Indicates the battery is currently alright in the wake of being low.

android.intent.action.BOOT_COMPLETED   -This is broadcast once, after the framework has completed the process of booting.

android.intent.action.BUG_REPORT  – Show action for reporting a bug.

android.intent.action.CALL   – Perform a call to somebody determined by the data.

android.intent.action.CALL_BUTTON  – The client pressed the “call” button to go to the dialer or other proper UI for setting a call.

android.intent.action.DATE_CHANGED  – The date has changed.

android.intent.action.REBOOT  – Have the device reboot.

Android Broadcasting Custom Intents

If you want that your android application itself generate and send custom intents then  then you will need to make and send those purposes by using the sendBroadcast() mehtod inside your activity class. On the off chance that you use the sendStickyBroadcast(Intent) method, the Intent is sticky, which means the Intent you are sending stays around after the broadcast is finished.

public void broadcastIntent(View view)
{
   Intent intent = new Intent();
   intent.setAction("com.androdevelopment.CUSTOM_INTENT");
   sendBroadcast(intent);
}

 

This intent com.androdevelopment.CUSTOM_INTENT can also be registered in similar way as we have regsitered system generated intent.

<application
   android:icon="@drawable/ic_launcher"
   android:label="@string/app_name"
   android:theme="@style/AppTheme" >
   <receiver android:name="MyReceiver">
   
      <intent-filter>
         <action android:name="com.androdevelopment.CUSTOM_INTENT">
         </action>
      </intent-filter>
   
   </receiver>
</application>

 

Example of Android Broadcast Receivers

This example will show you how to make BroadcastReceiver to catch custom intent. When you are acquainted with custom inten, then you can program your application to intercept framework produced intents. So we should take after the accompanying steps to adjust the Android application we made in Hello World Example tutorial

Steps                          Description

1   –    You will use Android studio to make an Android application and name it as My Application under a bundle com.example.My Application as clarified in the Hello World Example tutorial.

2 –      Modify  MainActivity.java to include broadcastIntent() strategy.

3  –     Create another java file called MyReceiver.java under the bundle com.example.My Application to characterize a BroadcastReceiver.

4 –     An application can deal with one or more custom and framework intents with no confinements. Each indent you need to block must be registered in your AndroidManifest.xml file utilizing <receiver…/> tag

5 –     Modify the default content of res/design/activity_main.xml file to incorporate a button to broadcast intent.

6 –    No need to change the string file, Android studio deal with string.xml document.

7 –    Run the application to launch Android emulator and confirm the consequence of the progressions done in the application.

Following is the content of the modified main activity file src/com.example.My Application/MainActivity.java. This file can include each of the fundamental life cycle methods. We have added broadcastIntent()method to broadcast a custom intent.

package com.example.My Application;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.content.Intent;
import android.view.View;

public class MainActivity extends Activity {

   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      }
   
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      getMenuInflater().inflate(R.menu.activity_main, menu);
      return true;
      }
   
   // broadcast a custom intent. 
   public void broadcastIntent(View view){
      Intent intent = new Intent();
      intent.setAction("com.androdevelopment.CUSTOM_INTENT");
      sendBroadcast(intent);
   }
}

 

Following is the content of src/com.example.My Application/MyReceiver.java:

package com.example.My Application;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class MyReceiver extends BroadcastReceiver {
   @Override
   public void onReceive(Context context, Intent intent) {
      Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
   }
}

 

Following will the modified content of AndroidManifest.xml file. Here we have added <service…/> tag to include our service:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.My Application"
   android:versionCode="1"
   android:versionName="1.0" >
   
   <uses-sdk
      android:minSdkVersion="8"
      android:targetSdkVersion="22" />
   
   <application
       android:icon="@drawable/ic_launcher"
       android:label="@string/app_name"
       android:theme="@style/AppTheme" >
       
       <activity
          android:name=".MainActivity"
          android:label="@string/title_activity_main" >
       
          <intent-filter>
             <action android:name="android.intent.action.MAIN" />
             <category android:name="android.intent.category.LAUNCHER"/>
          </intent-filter>
          
       </activity>
       
       <receiver android:name="MyReceiver">
       
       <intent-filter>
          <action android:name="com.androdevelopment.CUSTOM_INTENT">
          </action>
       </intent-filter>
       
       </receiver>
       
   </application>
</manifest>

 

Following will be the content of res/layout/activity_main.xml file to include a button to broadcast our custom intent –

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
   android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
   
   <TextView
      android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Example of Broadcast"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:textSize="30dp" />
      
   <TextView
      android:id="@+id/textView2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Andro Development "
      android:textColor="#ff87ff09"
      android:textSize="30dp"
      android:layout_above="@+id/imageButton"
      android:layout_centerHorizontal="true"
      android:layout_marginBottom="40dp" />
      
   <ImageButton
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageButton"
      android:src="@drawable/abc"
      android:layout_centerVertical="true"
      android:layout_centerHorizontal="true" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/button2"
      android:text="Broadcast Intent"
      android:onClick="broadcastIntent"
      android:layout_below="@+id/imageButton"
      android:layout_centerHorizontal="true" />

</RelativeLayout>

 

Following will be the content of res/values/strings.xml to define two new constants


<resources>    
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">My Application</string>
</resources>

 

How about we attempt to run our adjusted Hello World! application we simply modified. I accept you had made your AVD while doing android environment setup. To run the application from Android studio, open one of your project activity file and snap  Android Studio Run Icon  from the tool bar. Android Studio installs the application on your AVD and begins it and if all is well with your set-up and application, it will show taking after Emulator window

android broadcast receiver

Presently to broadcast our custom intent, we should tap on Broadcast Intent button, this will broadcast our custom plan “com.androdevelopment.CUSTOM_INTENT” which will be intercepted by our registered BroadcastReceiver i.e. MyReceiver and according to our implement logic a toast will show up on the base of the test system as takes after –

android broadcast receiver

You can try implementing other BroadcastReceiver to intercept system generated intents like system boot up, date changed, low battery etc.