Skip to main content

How to check internet connectivity in Android app using BroadcastReceiver


So let's get started with How to check internet connectivity in Android using BroadcastReceiver.

For this post I'm using Kotlin language.

Well lots of people are using simple method to get network connectivity using ConnectivityManager. But using that approach we will get network state only when we are calling that method. So how would I know that network state changed.

This will achieved using BroadcastReceiver. 

What is BroadcastReceiver?
BroadcastReceiver uses Publish-Subscribe pattern. Android app can send and receive messages from Android system and other apps. 
Android system sends broadcast when various system events occurred like device charging, network state changes.
Apps can register to receive specific broadcasts. When a broadcast is sent, the system automatically routes broadcasts to apps that have subscribed to receive that particular type of broadcast.

So for this scenario we need to add some changes in AndroidManifest.xml file

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
-  <uses-permission android:name="android.permission.INTERNET" />
-  <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

Now we need to register our Receiver in manifest file so whenever event occurred our app will get event message.


<receiver
android:name=".NetworkStateChangeReceiver"
android:enabled="true"    
android:exported="false">
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    </intent-filter>

</receiver>

android:enabled="true"
If true then broadcast receiver can be instantiated by the system. But application tag also have this element, so to enable broadcast receiver in application you need to make both element's value true

android:exported="false"


if false then broadcast receiver can not be receive message from sources outside it's application.


Intent-filter used to specifies the types of intent on which Activity or service will respond.



android.net.ConnectivityManager:
Class that answers queries about the state of network connectivity. It also notifies applications when network connectivity changes.

So let's create a BroadcastReceiver,

NetworkStateChangeReceiver.kt

Added 2 fields inside companion object, so we can access them in other
classes.

object
Bar { 
val bar1 = "bar1"
const val bar2 = "bar2"}


This is why const keyword is used before val in companion object. So Java compiler will compile fields into below code.



public final class Bar {
private static final java.lang.String bar1; public static final java.lang.String bar2;}



In onReceive method, intent created which will put state of network in
extras. By using isNetworkAvailable method I'm accessing network state
using connectivity manager.

So now we created BroadcastReceiver and registered it in Manifest file.
It's time to access those states in Activity.

BaseActivity.kt
Ignore that open keyword. I have created BaseActivity which will be
inherited by other activities. So in Kotlin you need to add open
keyword to base class.

Now we need to create instance of our broadcast receiver class
and register receiver.
Create intent filter which will have action that we mentioned in our
Broadcast receiver class.
Using LocalBroadcastManager receive message broadcast by our broadcast
receiver.

As we registered our broadcast receiver in onCreate() method, we need
to unregistered it in onDestroy() method.

Code

Here is the link of sample code https://github.com/sachinsandbhor/BroadCastReceiverSample

Comments

Popular posts from this blog

RxJava introduction for Android developer

RxJava is Java implementation of Reactive Extension. Basically it’s a library that composes asynchronous events by following Observer Pattern. You can create asynchronous data stream on any thread, transform the data and consumed it by an Observer on any thread. The library offers operators like map, combine, merge, filter and lot more that can be applied onto data stream.  Below are the list of schedulers available and their brief introduction. - Schedulers.io()  – This is used to perform non CPU-intensive operations like making network calls, reading disc / files, database operations etc., This maintains pool of threads. 

 - AndroidSchedulers.mainThread()  – This provides access to android Main Thread / UI Thread. Usually operations like updating UI, user interactions happens on this thread. We shouldn’t perform any intensive operations on this thread as it makes the app glitchy or ANR dialog can be thrown. 

 - Schedulers.newThre...

Get domain name from URL in android

Sample Code: String url="http://sports.in.msn.com/football-world-cup-2014/world-cup-animals-5"; String hostName=getDomainName(url); private CharSequence getDomainName(String shareURL) throws URISyntaxException {    URI uri = new URI(shareURL);    String domain = uri.getHost();     return domain; } above method return host name from given URL. You can get more from URL using below methods. uri.getProtocol(); uri.getAuthority(); uri.getHost(); uri.getPort(); uri.getPath(); uri.getQuery(); uri.getFile(); Output: protocol = http authority = sports.in.msn.com host = sports.in.msn.com port = -1 path = /football-world-cup-2014/world-cup-animals-5 query = null filename = /football-world-cup-2014/world-cup-animals-5