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 :
- Create your own receiver class which will extend the BroadcastReceiver class of the default android.content package.
- 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.
- 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.
- Now, in your manifest file register your receiver with the inbuilt intent filter and you are good to go.
- Register and unregister your receiver in your activity/fragment.
Now, let’s have a look at the code snippet.
CODE :
My Reciever–>
1 2 3 4 5 6 7 8 |
public class MyReciever extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { // write your logic for handling the data recieved in intent here } } |
Manifest file changes–>
1 2 3 4 5 |
<receiver android:name=".MyReciever"> <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/> <!--Replace this line with your desired action--> </intent-filter> </receiver> |
Activity file changes–>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public abstract classMyActivity extends AppCompatActivity { private MyReciever myReciever; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // other onCreate Code myReciever = new MyReciever(); registerReceiver(myReciever, new IntentFilter(/*Pass your intent filet here*/)); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(myReciever); } } |
If you want to have a look at the exact working code for a network change please check below.
Custom Broadcast Reciever
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 |
public class NetworkStateReciever extends BroadcastReceiver { protected Set<NetworkStateReceiverListener> listeners; protected Boolean connected; public NetworkStateReciever() { listeners = new HashSet<NetworkStateReceiverListener>(); connected = null; } public void onReceive(Context context, Intent intent) { if(intent == null || intent.getExtras() == null) return; ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo ni = manager.getActiveNetworkInfo(); if(ni != null && ni.getState() == NetworkInfo.State.CONNECTED) { connected = true; } else if(intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) { connected = false; } notifyStateToAll(); } private void notifyStateToAll() { for(NetworkStateReceiverListener listener : listeners) notifyState(listener); } private void notifyState(NetworkStateReceiverListener listener) { if(connected == null || listener == null) return; if(connected) listener.networkAvailable(); else listener.networkUnavailable(); } public void addListener(NetworkStateReceiverListener l) { listeners.add(l); notifyState(l); } public void removeListener(NetworkStateReceiverListener l) { listeners.remove(l); } public interface NetworkStateReceiverListener { public void networkAvailable(); public void networkUnavailable(); } } |
My Activity
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 |
public class MyActivity extends AppCompatActivity implements NetworkStateReciever.NetworkStateReceiverListener { // other code of the activity public NetworkStateReciever mNetworkStateReciever; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // other onCreate related code mNetworkStateReciever = new NetworkStateReciever(); mNetworkStateReciever.addListener(this); registerReceiver(mNetworkStateReciever,new IntentFilter(android.net.ConnectivityManager.CONNECTIVITY_ACTION)); } @Override public void networkAvailable() { Toast.makeText(BaseActivity.this, "Network Available", Toast.LENGTH_SHORT).show(); } @Override public void networkUnavailable() { Toast.makeText(BaseActivity.this, "Network Unavailable", Toast.LENGTH_SHORT).show();} } @Override protected void onDestroy() { super.onDestroy(); mNetworkStateReciever.removeListener(this); unregisterReceiver(mNetworkStateReciever); } } |
Manifest file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" package="com.example.Myapplication"> <application android:name=".MyApplication" android:allowBackup="true" android:icon="@mipmap/my_launcher" android:label="@string/app_name" android:largeHeap="true" android:supportsRtl="true" android:theme="@style/AppTheme" android:vmSafeMode="true"> </-- othe manifest code --> <receiver android:name=".NetworkStateReciever"> <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> </intent-filter> </receiver> </application> </manifest> |
That’s all.
Keep coding and keep sharing.