There are many different types of Android events that we may encounter in which we use a broadcast receiver. These events are low battery, wifi availability, incoming call, bluetooth device connected, incoming SMS, charger (connected or disconnected), and others.
For example, in the case of a low battery event, you want to stop your app from using any backend data polling mechanism. To listen to these events you will need a listener which will only listen to particular events for which it is registered. The listener is nothing but a broadcast receiver. You register this broadcast receiver either in the manifest file or in the code. These events are intents. So, whenever these kinds of events happen, an intent is triggered. Here the term intent is actually a broadcast, and if a broadcast receiver is registered in the manifest file or code to listen to these events, then it will respond to these broadcast intents.
Android OS sends broadcasts to apps when any event happens in the app or in the system. Broadcast receivers helps our app communicate with Android OS and other apps.
There are two different methods to register a broadcast receiver.
Statically (manifest-declared) - This receiver can be registered via the AndroidManifest.xml file.
Dynamically (context-registered) - This registers a receiver dynamically via the Context.registerReceiver() method.
Receive broadcast app has to extend the BroadcastReceiver abstract class and override the onReceive() method. This method is called by the Android system.
onStop() or onPause():- These methods are used for unregistering a broadcast receiver of the activity.
1
2
3
4
@Override protected void onPause() {
unregisterReceiver(myReceiver);
super.onPause();
}
Add support library dependency build.gradle file.
1
compile‘ com.android.support: support - v4: 23.4 .0’
In the latest version of Android Studio, no additional dependency is required.
1
2
3
4
5
6
7
LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(context);
sendBroadcast(): -This method sends local broadcasts.
// Create intent with action
Intent localIntent = new Intent(“CUSTOM_ACTION”);
// Send local broadcast
localBroadcastManager.sendBroadcast(localIntent);
Now we will create a broadcast receiver that can respond to the local-broadcast action.
1
2
3
4
5
6
7
private BroadcastReceiver listener = new BroadcastReceiver() {
@override
public void onReceive(Context context, Intent intent) {
String data = intent.getStringExtra(“DATA”);
Log.d(“Received data: ”, data);
}
};
Dynamically (context-registered) registered receivers must be unregistered when they are no longer necessary.
localBroadcastMannger.unregisterReceiver(myBroadcastReceiver);
Permission parameter - Only the broadcaster who has requested permission to receive a broadcast from a registered broadcast receiver can send the intent to that receiver.
Example:
1 2 3 4 5 6 7
<receiver android:name=”.MyBroadcastReceiver” android:permission=”android.permission.SEND_SMS”> <intent-filter> <action android:name=”android.intent.action.AIRPLANE_MODE”/> </intent-filter> < /receiver>
android:exported - If this attribute is set as “false” in the manifest file then it will restrict receiver broadcasts from sources outside of the application.
We can specify permission when sending a broadcast so that only receivers who have requested that permission can receive the broadcast.
1
sendBroadcast(new Intent(“com.example.NOTIFY”), Manifest.permission.SEND_SMS);
We can send local broadcasts with LocalBroadcastManager.
Example:
build.app
1
2
3
4
5
6
android {
...
dependencies {
...
compile‘ com.android.support: support - v4: 23.4 .0’
}
AndroidManifest
1 2 3 4 5
<manifest ...> <uses-permission android:name="android.permission.SEND_SMS"/> <application ....> </application> </manifest>
activity_main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <EditText android:id="@+id/edsend" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="10sp" android:layout_marginTop="10sp" android:layout_marginRight="10sp" android:layout_marginBottom="10sp" android:ems="10" android:gravity="center_horizontal" android:hint="@string/Edit_SMS" android:inputType="textPersonName" /> <EditText android:id="@+id/eddelived" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="10sp" android:layout_marginTop="10sp" android:layout_marginRight="10sp" android:layout_marginBottom="10sp" android:ems="10" android:gravity="center_horizontal" android:hint="@string/Edit_Phone" android:inputType="phone" /> <Button android:id="@+id/bsend" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="10sp" android:clickable="true" android:gravity="center_horizontal" android:onClick="btn_sendSMS_OnClick" android:text="@string/Button_Send" /> </LinearLayout>
MainActivity.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package com.example.smssend;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditTexte edsend, eddelived;
Button bsend;
String send = "Send_SMS";
String delivered = "Delivered_SMS";
PendingIntent sendPI, deliveredPI;
BroadcastReceiver smsSendReciver, smsdeliveredReciver;
int MY_Permisson_Request_Code = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edsend = findViewById(R.id.edsend);
eddelived = findViewById(R.id.eddelived);
bsend = findViewById(R.id.bsend);
sendPI = PendingIntent.getBroadcast(this, 0, new Intent(send), 0);
deliveredPI = PendingIntent.getBroadcast(this, 0, new Intent(delivered), 0);
}
@Override
protected void onResume() {
super.onResume();
smsSendReciver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(MainActivity.this, "SMS_send", Toast.LENGTH_SHORT)
.show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(MainActivity.this, "Generic fail", Toast.LENGTH_SHORT)
.show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(MainActivity.this, "NO Service", Toast.LENGTH_SHORT)
.show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(MainActivity.this, "Rasio off", Toast.LENGTH_SHORT)
.show();
break;
}
}
};
smsdeliveredReciver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(MainActivity.this, "SMS_Delivered", Toast.LENGTH_SHORT)
.show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(MainActivity.this, "SMS not deliverd", Toast.LENGTH_SHORT)
.show();
break;
}
}
};
registerReceiver(smsSendReciver, new IntentFilter(send));
registerReceiver(smsdeliveredReciver, new IntentFilter(delivered));
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(smsSendReciver);
unregisterReceiver(smsdeliveredReciver);
}
public void btn_sendSMS_OnClick(View v) {
String message = edsend.getText()
.toString();
String number = eddelived.getText()
.toString();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[] {
Manifest.permission.SEND_SMS
},
MY_Permisson_Request_Code);
} else {
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(number, null, message, sendPI, deliveredPI);
}
}
}