1. Home
  2. Training Library
  3. Programming
  4. Programming Courses
  5. Intent & Lifecycles in Android App Development

Receivers in Android App Development

Contents

keyboard_tab

The course is part of this learning path

Start course
Overview
Difficulty
Intermediate
Duration
2h 15m
Students
4
Description

This course focuses on lifecycles and intent in Android and then moves on to look at services, receivers, and Android app binding.

Intended Audience

This course is intended for anyone who wants to learn how to start building their own apps on Android.

Prerequisites

To get the most out of this course, you should have some basic knowledge of the fundamentals of Android.

Resources

Course GitHub repo: https://github.com/OakAcademy/android-app-development-with-kotlin/tree/main/Section%207%20-%20Intent%20and%20Lifecycle/Intent 

 

Transcript

Broadcast receivers. Hello, everyone. Now, we're going to talk about broadcast receivers in  Android devices in this particular video. The broadcast receiver is a messaging system used on  Android devices, but this messaging system is used between the  Android operating system and  Android applications. The  Android operating system shares device-related information with  Android applications. Bet you didn't know that, huh? So, this device-related information can be just simple stuff like the device battery level, whether it's connected to Wi-Fi or not, whether the device starts to charge, or is the device in airplane mode or not, all that kind of stuff. So, if the application wants to know some of this information or all of it, it will subscribe to the operating system in order to get this information.

So, when these system events occur, the operating system sends a broadcast message to any of the subscribed applications. The  Android operating system sends these messages when the system events occur. So, this is really important because whenever one of the system events occurs, the Android operating system sends broadcast messages at that particular time. For example, if you want your application to learn when the device battery is low, you will need to subscribe your application to that specific system event. And when the device battery is low, the  Android operating system will send a message to your application. That's why it's called a broadcast message. Or if you want your application to know when the device is connected to Wi-Fi, you can subscribe your application to that system event. And whenever the device is connected to Wi-Fi, the  Android operating system will send a broadcast message to your application. Now when your  Android device gives a warning to you that the battery is low, it also sends this message to all of the subscribed applications. Also, when the  Android device switches into airplane mode or the user does that, the system sends this message to all of the subscribed applications. So, all this makes sense, right? So, how are we going to use this information for  Android application?

So, our application subscribes to the information that we want. Android operating system does not send every bit of information or system events. We subscribe to system events, whichever one we will need in our particular application. I cannot be more clear than that. So, we take information from the system. But where are we going to use this information? For example, you develop an application and this application saves user photos on a server. Now, such an application allows the user to access their photos from anywhere. Okay, it's a great feature. Really useful. But how will you send the photos to the server?

If you send every photo to the server when the photo was taken, it will pretty rapidly use up the user's mobile data, right? Because a user can even take hundreds of photos in a few seconds. So, this is probably not a good feature for an application. Nobody wants to use that kind of data-sucking application, right? So, what you do is you save photos in the device memory. And then when the device is connected to Wi-Fi, you can then send the photos to the server. So, it's this kind of thinking and this kind of feature that will reduce the user's mobile data consumption. That's how you get a good reputation by the way. So, if you want to develop this kind of application, you will need to learn when the device is connected to Wi-Fi. Your application can subscribe to system events, and when the device is connected to Wi-Fi, the  Android operating system sends a broadcast receiver message to the application. And then after this message, your application starts to send the user photos to the server. Now, also when the device is disconnected from Wi-Fi, the system will send a message again to the application and your application will stop sending photos to the server, right?

Now, where else do you figure we can use this broadcast receiver? Well, let's say for example, applications that verify by message can use the broadcast messaging system. You know, many applications are using message validation systems such as WhatsApp and Viber, and some of them when the message comes in, read the message automatically. So, you can develop this kind of application using broadcast messaging. Your application subscribes to the system event. And when a new message comes into the phone, your application will know this. And then after that your application can read this message automatically. Now let me give you another example when device battery is low, the system will send a message to the subscribed applications. So, after the application gets the message, the application can stop its background tasks. So, then this both reduces the device battery consumption and it prevents sudden interruption of the background task. And then when the battery level is normal, the system sends another message to the applications. Then after they get this message, the applications can then restart their background tasks. So, the use of broadcast messages when designing an application is really important for the more efficient and better quality applications, which is what you want to build, I'm sure.

Okay, so I also want to mention this. So, broadcast messaging system can be used between two applications. That's right. We're going to step it up. It means that one application can send a broadcast message to another application, but most of the time it's used between the  Android operating system and  Android applications. Okey-dokey, now before opening  Android Studio, I do want to mention that there are two different methods to define the broadcast receiver. So, the first one of these is the definition made in the manifest file. The second is the context-registered receiver method made in the  Kotlin class. So, if your  app targets  Android 8 or higher, that's 8.1 or higher, you cannot use the manifest to declare receiver from most implicit broadcasts. Which means broadcast  that don't target your app specifically. You can still use a context-registered receiver when the user is actively using your app though. Right?

So, in this lesson we're going to do two examples. We're going to do it both ways. But we're going to test the example that we will make using the manifest file in an emulator with API level 25. All right, so let's do it. Let's go to  Android Studio, and I'll create a new  Android Studio project. And if you want to you can just use your previous project. If we want to take broadcast messages, first of all, we'll need to create a receiver class. I will right click on the MainActivity class and after that select new Kotlin class file. All right, so I'll need to give it a name, name can be BroadcastExample, press enter. Okay, so now we have a BroadcastExample class. Also, this class needs to extend the broadcast receiver class. So, after the colon, all right, BroadcastReceiver. After that, we'll need to implement a method. I'll just click here, select Implement members. So, in here I select the onReceive method, click 'OK'.

Now,  Android Studio adds the onReceive method. Now, I want you to notice that this method has got two parameters here. I want to change this parameter names to make more sense. So, I'll write context instead of p0. And I'll write intent instead of p1. All right. Now, after that, I'll just write my codes in the onReceive method. Now, before I continue, I do need to define this class in the manifest file. All right? Just like I said in the beginning there are two ways to take broadcast receivers. The first one is manifest-declared receivers. The second one is context-registered receivers. All right? We are going to learn both of them in this video. Don't worry. But we'll start with manifest-declared receivers. So, that means opening up the manifest file, and I'll define the broadcast example class under the activity tag. After opening a new tag, I'll just write receiver, press enter, and the name will be BroadcastExample that we've just created.

Now, after that, I'll just close the 'receiver' tag, pressing the 'shift' and '<' keys on the keyboard. And inside the 'receiver' tag, I'll open up a new tag. This tag will be the intent-filter tag. And then lastly, inside the intent-filter tag, I'll use the action tag. So, we're going to select the broadcast receiver type just by using the action tab. And by that, I mean which system events I want to know when it happens, I will select here. And you can see here which system events you can take with the receiver. For example, action power connected and disconnected. So, this event sends a receiver to the application when the device is connected to the charger or disconnected from the charger. Here's another one, airplane mode.

So, obviously when the device switches to airplane mode, the system will send a receiver to the application. So, another two are 'BATTERY_LOW', 'BATTERY_OKAY'. You can, of course, learn the device charge status using these methods. Another one is 'DEVICE_STORAGE_LOW'. It's also very good method. So, when the device storage is low, your application can take a receiver and then after that you can start a background task to delete some useless files in the devices storage. So, there are a lot of methods here and you can read through and play with every single one of them on your own time. No, but you should go through them. For example, reboot. So, this method will send a broadcast message when the device is rebooted. Another two here are 'SCREEN_ON and OFF'. So, if you want to start something when the device screen is on or off, you can use these method.

So, I'll select airplane mode for this example  and then after that I'll close the action tag pressing the '/' key on the keyboard. Now, if you were paying attention, you'll see that we got a warning. It's because we need to set the  Android exported property. So, I'm making the  Android exported property to be true. And if this property is true, the broadcast receiver can receive events sent by the same or other applications. If it's false, broadcast receiver can receive events sent by the same application.

Now, when the device switches to airplane mode, the system will send a broadcast receiver to my BroadcastExample class. I'll take this message in the on received method and then after that I can do whatever I want with this message. So, for this example, I want to show a toast message when the device switches to airplane mode.  So, I'll just write in here 'Toast.makeText'. Now, it's going to take three parameters. So, the first one, context. The second one is the message itself. And of course, the message could be something obvious like 'The device is in airplane mode.' And the last one is going to be the toast message time. So, I'll write 'Toast.LENGTH_LONG' and then lastly '.show'. So, now when the device switches to airplane mode, this system will send a broadcast message to the broadcast example class. After taking in this message, the broadcast example class will show a toast message to the user, and if you want another thing or start another task, I can just write it in the on received method.

But for now let's just run the application and see how it works or not. If you do notice this, I am testing it on an emulator with API level 25. So, if you test on emulator with an API level above 25, you're not going to be able to see the broadcast messages. Later on, we will be using an API level 30 emulator in the context registered receiver method. We're going to do that soon, but please make a note of it and be careful with it. So, you can see the application opens, and I will change to airplane status. Now the device is in normal mode,  so I'll change it. And you see when I change the airplane mode status, it shows me a toast message. I'll change the airplane status to normal again, and there you go, the toast message appears.

So, this method notifies the application when the device changes its airplane mode. And that means when the device switches to airplane mode or switches back to normal mode, the system will send a broadcast message. But for now, this system shows us the exact same toast message. But we'll need to find out if airplane mode is on. So, how I understand, the device switches to airplane mode or normal mode. Well, I need to learn if the device is in airplane mode or not. So, while the system is sending broadcast messages, it also sends a Boolean parameter. So, if I use this Boolean parameter. I can learn that device status. When airplane mode is open the parameter will be true, and when airplane mode is off the parameter will be false. So, I need to create a container to catch this Boolean parameter.

So, I just write, 'val isAirPlaneMode : Boolean = intent.getBooleanExtra()'. So, this method is going to take two parameters. The first one is the keyword and it will take the message using this keyword. The system sends the message with the same keyword. In fact, the keyword is "state". The second one is the 'defaultValue'. I'll just give the 'defaultValue' to be false. Also, I want to put the '!!' in here, and that is for the non-known assert. If the device switches from normal mode to airplane mode, this system will send true. If the device switches from airplane mode to normal mode, the system will send false. So, I need to create an 'if else' statement. So, I'll write, 'if (isAirplaneMode)', that means, if the isAirplaneMode variable is true, it will show this toast message. 'else', it will show another toast message. And the message will be, "The device is not in airplane mode". So, let's run it again and see.

Application opens,  so I'll switch to airplane mode and it shows the toast message. The device is in airplane mode. Now, I'll switch to normal mode and it shows a toast message. The device is not an airplane mode. I'm right. So, this is how manifest declared broadcast works. So, let's have a look at the other system events using this broadcast message. There is another way, of course, to take broadcast receivers, it is context registered receivers. I want to show you this method as well, you can use context registered receiver methods at all API levels but the manifest declared method is used in the API level 25 or lower. So, that means I got to first delete this declaration in the manifest file because I'm not going to be using it this way anymore.

So, I'm not going to change anything in the broadcast example class. I will go to the main activity class and create an object of the broadcast example class. So, that means I got it write here, 'var br = BroadcastExample()'. After that, in the onCreate method, I will create an object of intent filter class. I will write, 'val filter = IntentFilter()' and in the second line, 'filter.addAction()'. And inside () I will write 'Intent.' and after putting that '.' in there, you can see all of the methods will show up that you can use in the manifest file are here now. And you can select one of these, for example, 'AIRPLANE_MODE, SCREEN_ON and OFF'. Boot completed. All of the methods are here. I want to select 'AIRPLANE_MODE_CHANGED'. After that I'll just write, 'this.registerReceiver'. This method will take two parameters. The first one is the object of the BroadcastReceiver Class br. The second one is the object of the intent filter class filter. So, now it's going to work.

So, when the application works, it's going to take two receivers in the receiver example class. While the system is sending, BroadcastReceiver will also send a Boolean parameter. If it is true, it will show this toast message. If it is false, it's going to show another toast message. But before I write, I will need to say something. I will register this method in the onStart method and unregister it in the onStop method. Now, why is that? Because it's going to be taking receivers when the application is open, and it will not take receivers when the application is closed. So, I will call the onStart method. I will cut these codes and paste them inside the onStart method. So, now we can unregister in the onStop method. I'll write the onStop method, 'this.unregisterReceiver(br)'. So, when I unregister the receiver, I will write just the object of the broadcast receiver. So, now let's run the application. So, this time I'm going to test the app in API 30 emulator. So, the application opens. Device is in normal mode now.

So, when I switch to airplane mode, see how it shows a toast message. The device is in airplane mode. I'll switch the device to normal again and there is a toast message, 'The device is not in airplane mode'. So, if I close the application, will it continue to take a receiver? Well, I close the application. Change the device, airplane mode status and you see it does not show a toast message. So, that means the application will not take broadcast receivers anymore. That's why I unregistered it in the onStop method. So, when the application passes to the onStop method, it will not take any broadcast receivers anymore. The application will take broadcast messages when the application is in the foreground. But of course, you can change that according to your needs. It's entirely up to you. But whatever your choice is, we've got to the end of this video. I certainly hope it was useful for you. We're going to be playing around with it more later on. So, I want to see you in the next video.

 

About the Author
Students
86
Courses
23
Learning Paths
1

Mehmet graduated from the Electrical & Electronics Engineering Department of the Turkish Military Academy in 2014 and then worked in the Turkish Armed Forces for four years. Later, he decided to become an instructor to share what he knew about programming with his students. He’s currently an Android instructor, is married, and has a daughter.

Covered Topics