Android Tutorial

Android Tutorial Android Toast Button Widget In Android Tutorial Imageview Widget In Android Android Date Picker Example Android Time Picker Example Android Operating System Android Activity Android Architecture Android Content Providers Android Edittext Android Emulator Android Fragments Android Gridview Android Broadcast Receivers Event Handling In Android What Is Android Studio Android Navigation Drawer Android Recyclerview Android Scrollview Android Navigation Android Operating System Android ListView Android Studio Resources Android Studio's Layout Editor Android TextView Android Styles and Themes How To Show Image On An Android Application How To Insert An Email In Android Application In Android Version 8 How To Insert The Mobile Number On An Android Application Using Edittext Difference between android developer and web AdapterViewFlipper in Android with Example Android 9.0 Pie vs. Android 10, which one is better Android Development or Web Development which one is the best to choose Android Project Folder Structure Assets folder in Android How to reduce the size of APK in Android Top 7 Android App Development Books Top Programming Languages for Android Development Android Navigation Application Components Difference between android developer and web developer Event Handling in Android How to reduce the size of APK in Android Top 7 Android App Development Books Top Programming Languages for Android Development AdapterViewFlipper in Android with Example Android 9.0 “Pie” vs. Android 10, which one is better Android Development or Web Development which one is the best to choose Android EditText Android Fragments How to Update Gradle in Android Studio Navigation Drawer ScrollView What is Android Studio? Android Architecture Android Content Providers

Android Broadcast Receivers

Android applications can send or receive broadcast messages from the Android operating system and other Androidapplications, like the publish-subscribe design pattern. When an event of interest happens,these broadcasts are sent.

For example, the Android OS sends broadcasts when a variety of system events happen, such as when the devicerestarts or the device goes into airplane mode. Applications can also send personalized broadcasts, for example, to notify other applications of something that they might interact with.

Some use cases of the Broadcast Receiver are:

1. Communication between multiple apps

2. Create Bound Services within the Applications

3. Respond to system events that occur within the device

A BroadcastReceiver is an Android Class that receives these broadcasts and performs services accordingly.

Broadcast Receiversare divided into 2 types as follows:

  • Static Broadcast Receivers: Static broadcastreceivers also known as manifest-declared receivers are specified in the android manifest file and works even if the application is shut down.
  • Dynamic Broadcast Receivers: Dynamic broadcast receivers work only if the application is working or minimized.

Static Broadcast Receivers

1. Declare the element in your application's manifest.

<receiver android:name=".ExampleBroadcastReceiver" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.INPUT_METHOD_CHANGED" /
>
</intent-filter>
</receiver>

2. Create a BroadcastReceiver’s subclass

public class ExampleBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "ExampleBroadcastReceiver";
@Override
public void onReceive(Context context, Intent intent) {
StringBuilder str= new StringBuilder();
str.append("Action: " + intent.getAction() + "\n");
str.append("URI: " + intent.toUri(Intent.URI_INTENT_SCHEME).toString() + "\n");
String log = str.toString();
        Log.d(TAG, log);
        Toast.makeText(context,log,Toast.LENGTH_SHORT).show();
    }
}

Dynamic Broadcast Receivers

1. Create a Receiver’s instance

BroadcastReceiver Newbr = new MyBroadcastReceiver();

2. Create and add intent-filters for the Receivers

IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
this.registerReceiver(Newbr, filter);

Sending a Broadcast

To send a broadcast, add the following code to your activity class file

Intent intent = new Intent();
intent.setAction("com.example.broadcast.MY_NOTIFICATION");
intent.putExtra("data", "Life goes on.");
sendBroadcast(intent);

Most of the broadcast can only be received by the dynamic receivers since API level 21, so we have implemented dynamic receivers in our project example given below. Some static fields are defined in the Intent class, which can be utilized to broadcastvarious events. We consider the flight mode change as a broadcast event, but the broadcast log can be used for many events.

Some of the system-wide generated intents are-

    IntentDescription Of Event
android.intent.action.BATTERY_LOW :Shows low battery notification on the device.
android.intent.action.BOOT_COMPLETEDShows that the system has completed booting
android.intent.action.CALLTo make a call to someone mentioned by the data
android.intent.action.DATE_CHANGED Shows that the date has altered
android.intent.action.REBOOTShows that the device has gone into reboot
android.net.conn.CONNECTIVITY_CHANGEThe mobile network or Wi-Fi connection is altered (or reset)
android.intent.ACTION_AIRPLANE_MODE_CHANGEDThis shows that airplane mode has been switched on or off.

Example

Below is an example project showing how to make the broadcast Receiver and how to register and utilizethem for a specific event in the android application.

1) Create a New Project

Create a new android project in Android Studio. If you come across any problem in creating a new project, please refer to Android Studio Tutorial.

2) Modifying the activity_main.xml file

Open the activity_main.xml file and the code for the activity_main.xml file will be as follows:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:background="#FFEB3B"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity">
</androidx.constraintlayout.widget.ConstraintLayout>

3) Modifying the MainActivity.java file

Go to the MainActivity java file and make the following changes as mentioned in the following code:

import android.content.Intent;
import android.content.IntentFilter;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;


public class MainActivity extends AppCompatActivity {


    AirplaneModeSwitchReceiver airplaneModeSwitchReceiver = new AirplaneModeSwitchReceiver();


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


@Override
protected void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);
        registerReceiver(airplaneModeSwitchReceiver, filter);
    }


@Override
protected void onStop() {
super.onStop();
        unregisterReceiver(airplaneModeSwitchReceiver);
    }
}

4) Make airplaneModeSwitchReceiverclass

Go to app > java > your package name(in which the MainActicity is present) > right-click > New > Class file and name the files as AirplaneModeSwitchReceiver. Below is the code for the AirplaneModeSwitchReceiver file.

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


public class AirplaneModeSwitchReceiver extends BroadcastReceiver {


@Override
public void onReceive(Context context, Intent intent) {
if(checkAirplaneMode(context.getApplicationContext())){
            Toast.makeText(context, "AirPlane mode is on", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(context, "AirPlane mode is off", Toast.LENGTH_SHORT).show();
        }
    }


private static boolean checkAirplaneMode(Context context){
return Settings.System.getInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
    }
}
Broadcast Receivers