Easy way to IT Job

Android Broadcast Receiver – Tutorial 5

Android Broadcast Receiver – Tutorial 5

Published On: December 28, 2022

Android Broadcast Receiver – Tutorial 5

The Android Broadcast Receiver is a component of Android that is inactive but serves the purpose of listening for system-wide broadcast events or intents. The application is triggered into action whenever any of these events take place, and it does so by either adding a notification to the status bar or carrying out a job. Android’s Broadcast Receiver does not have any sort of user interface, in contrast to activities. Android broadcast receiver is typically constructed to assign duties to services based on the type of intent data that is received. This can be done regardless of whether or not the data is encrypted. The following are some of the more significant intentions that are generated across the entire system.

  • intent.action. BATTERY LOW: This status indicates that the device’s battery is running low.
  • intent.action.BOOT COMPLETED: It is a signal that is only ever sent out once after the system has successfully completed the booting process.
  • intent.action. CALL: To make a call to the person whose information is contained.
  • intent.action data.DATE CHANGED: The date has been adjusted.
  • intent.action.REBOOT: You will need to force a reboot of the device
  • net.conn.CONNECTIVITY CHANGE: Alterations are being made to either the cell network or the wifi connection (or reset)

Join the best Android training in Chennai to hone your skills in Android application development.

Android’s built-in Broadcast Receiver

The following are the two steps that need to be taken in order for us to successfully set up an Android Broadcast Receiver in an Android application.

  • Initiating the Creation of a BroadcastReceiver
  • Adding a BroadcastReceiver to Your Account

Initiating the Creation of an Android Broadcast Receiver

Let’s move rapidly through the process of implementing a specialized Android Broadcast Receiver, as seen below.

public class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
}

@Override
public void onReceive(Context context, Intent intent) {

Toast.makeText(context, “Action: ” + intent.getAction(), Toast.LENGTH_SHORT).show();
}
}

When it comes to Android Broadcast Receiver, the onReceiver() method is abstract as well, making the class itself abstract. When any event takes place, the onReceiver() function is the first one to be called on the Broadcast Receivers that have been registered. All of the additional data is included in the message that is sent along with the intent object. It is also possible to make use of a Context object, which can be done by calling context.startActivity(myIntent) or context.startService(myService), respectively, when beginning an activity or a service.

Adding the Broadcast Receiver to the Android app’s registration

There are two different approaches to registering an Android Broadcast Receiver.

Using the AndroidManifest.xml file to define it, as is displayed further down.

<receiver android:name=”.ConnectionReceiver” ><intent-filter>

<action android:name=”android.net.conn.CONNECTIVITY_CHANGE” />

</intent-filter>

</receiver>

Through the utilization of intent filters, we communicate to the system that any intent that is a match for our sub elements should be sent to a certain broadcast receiver. 3. By defining it using a programming language The code snippet that follows provides an example of how to register a broadcast receiver using programming.

IntentFilter filter = new IntentFilter();intentFilter.addAction(getPackageName() + “android.net.conn.CONNECTIVITY_CHANGE”);

MyReceiver myReceiver = new MyReceiver();

registerReceiver(myReceiver, filter);

The following code snippet can be implemented into the activity’s onStop() or onPause() functions in order to unregister a broadcast receiver.

@Overrideprotected void onPause() {

unregisterReceiver(myReceiver);

super.onPause();

}

Transmitting Broadcast intents from Activity

It is possible to communicate an intent to all of the linked BroadcastReceivers by utilizing the following snippet.

Intent intent = new Intent();intent.setAction(“com.journaldev.CUSTOM_INTENT”);

sendBroadcast(intent);

It is imperative that the aforementioned action be added either programmatically or in the intent filter tag of the manifest. Let’s build an application together that can respond appropriately to incoming data regardless of whether it comes from a network change event or a user-defined purpose.

Structure of BroadcastReceiver in the Android Project

The Description Of Connection Receiver.java Class

Code for Android Broadcast Receiver

The activity_main.xml file has a button that transmits a broadcast intent.

<?xml version=”1.0″ encoding=”utf-8″?><RelativeLayout xmlns:android=”https://schemas.android.com/apk/res/android”

xmlns:tools=”https://schemas.android.com/tools”

android:layout_width=”match_parent”

android:layout_height=”match_parent”

android:paddingBottom=”@dimen/activity_vertical_margin”

android:paddingLeft=”@dimen/activity_horizontal_margin”

android:paddingRight=”@dimen/activity_horizontal_margin”

android:paddingTop=”@dimen/activity_vertical_margin”

tools:context=”com.journaldev.broadcastreceiver.MainActivity”>

<Button

android:layout_width=”wrap_content”

android:layout_height=”wrap_content”

android:id=”@+id/button”

android:text=”Send Broadcast”

android:layout_centerVertical=”true”

android:layout_centerHorizontal=”true” />

</RelativeLayout>

The MainActivity.java is written below

package com.journaldev.broadcastreceiver;import android.content.Intent;

import android.content.IntentFilter;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.util.Log;

import android.view.View;

import android.widget.Button;

import butterknife.ButterKnife;

import butterknife.InjectView;

import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {

ConnectionReceiver receiver;

IntentFilter intentFilter;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

ButterKnife.inject(this);

receiver = new ConnectionReceiver();

intentFilter = new IntentFilter(“com.journaldev.broadcastreceiver.SOME_ACTION”);

}

@Override

protected void onResume() {

super.onResume();

registerReceiver(receiver, intentFilter);

}

@Override

protected void onDestroy() {

super.onDestroy();

unregisterReceiver(receiver);

}

@OnClick(R.id.button)

void someMethod() {

Intent intent = new Intent(“com.journaldev.broadcastreceiver.SOME_ACTION”);

sendBroadcast(intent);

}

}

In the line of code that you just saw, we have added another programmatically-registered custom action. The following snippet is where the ConnectionReceiver is declared in the AndroidManifest.xml file:

<?xml version=”1.0″ encoding=”utf-8″?><?xml version=”1.0″ encoding=”utf-8″?>

<manifest xmlns:android=”https://schemas.android.com/apk/res/android”

package=”com.journaldev.broadcastreceiver”>

<uses-permission android:name=”android.permission.INTERNET” />

<uses-permission android:name=”android.permission.ACCESS_NETWORK_STATE” />

<application

android:allowBackup=”true”

android:icon=”@mipmap/ic_launcher”

android:label=”@string/app_name”

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=”.ConnectionReceiver”>

<intent-filter>

<action android:name=”android.net.conn.CONNECTIVITY_CHANGE” />

</intent-filter>

</receiver>

</application>

</manifest>

The description of ConnectionReceiver.java class is given below.

public class ConnectionReceiver extends BroadcastReceiver {

@Overridepublic void onReceive(Context context, Intent intent) {

Log.d(“API123”,””+intent.getAction());

if(intent.getAction().equals(“com.journaldev.broadcastreceiver.SOME_ACTION”))

Toast.makeText(context, “SOME_ACTION is received”, Toast.LENGTH_LONG).show();

else

{

ConnectivityManager cm =

(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo activeNetwork = cm.getActiveNetworkInfo();

boolean isConnected = activeNetwork != null &&

activeNetwork.isConnectedOrConnecting();

if (isConnected) {

try {

Toast.makeText(context, “Network is connected”, Toast.LENGTH_LONG).show();

} catch (Exception e) {

e.printStackTrace();

}

} else {

Toast.makeText(context, “Network is changed or reconnected”, Toast.LENGTH_LONG).show();

}

}

}

}

In the line of code that you just looked at, we are checking the intent action that causes the onReceive() method to be triggered, and based on that, we are displaying the toast. Note: In the manifest, you must include the attribute android:exported=false in order to prevent third-party programs from accessing the broadcast receiver. When we send out a broadcast, it is feasible for the applications that are not part of our system to also get it. If this limitation is specified, then this problem can be avoided. The output app will be shown in action further below.

Structure Of Broadcast Receiver

There are three separate ways to send broadcasts, and they are as follows:

1- The sendOrderedBroadcast(Intent, String) method delivers broadcasts one at a time to a single listener.

2-The sendBroadcast(Intent) method transmits broadcasts to all receivers in an order that is not prescribed by the method.

3-The manager of the local broadcasts.

The sendBroadcast method transmits broadcasts to receivers that are located within the same application as the sender.

Hope this tutorial is useful to you in bringing insights into Android broad receiver. Feel free to post your doubts in the comment section. Learn about Android programs by enrolling in Android training in Chennai.

Just a minute!

If you have any questions that you did not find answers for, our counsellors are here to answer them. You can get all your queries answered before deciding to join SLA and move your career forward.

We are excited to get started with you

Give us your information and we will arange for a free call (at your convenience) with one of our counsellors. You can get all your queries answered before deciding to join SLA and move your career forward.