Start a Project

Creating Custom Broadcast Receiver in Android

In this blog, we will learn about how to create Custom Broadcast Receiver in Android.

While app development there is many times a need to create your own receiver that can help you connect through changes in the device on which the application is running and you need to render these changes at runtime, like on notification received or receiving an SMS that might be in relation to your application.

I felt the need to create a receiver and implement it using an interface so that my whole application can be aware of the internet connection status of the device and I can update the use case as per the scenario.

One way, of course, was to create a check before every call and proceed accordingly but when you have many activities this would be a much more time-consuming and boring approach. So, I thought of creating a small Broadcast Reciever, that can detect the network change and help me achieve my purpose.

Implementing this was very easy, this indeed is very similar to using interfaces. Let’s start.

APPROACH :

  1.  Create your own receiver class which will extend the BroadcastReceiver class of the default android.content package.
  2.  You will need to override the onRecieve() method, which will take context and intent as params. This is the heart of your receiver, so you need to write the code in it very aptly as this will only allow you to receive the data from your device to your Application.
  3. If you want to create some methods that you need to trigger inside your activity/fragment, create an interface in this class. If you just need this once you can jsut go ahead without the interface also.I have created an interface.
  4. Now, in your manifest file register your receiver with the inbuilt intent filter and you are good to go.
  5. Register and unregister your receiver in your activity/fragment.

Now, let’s have a look at the code snippet.

CODE :

My Reciever–>

Manifest file changes–>

Activity file changes–>

If you want to have a look at the exact working code for a network change please check below.

Custom Broadcast Reciever

My Activity

Manifest file

That’s all.

Keep coding and keep sharing.

Exit mobile version