Broadcastreceiver to get network state change
Posted By : Jitendra Negi | 27-Jun-2016
You can easily check internet wherever you required but sometimes as per different scenarios we have to check or get the state of internet while moving from one screen to others or in a idle state.
So I am explaining that how to get Network State.
Firstly we need following permission in order to access network state. Add following permission to your AndroidManifest.xml file.
Now create a class to check internet
import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; public class InternetConnection { public static boolean isInternetConnected(Context context) { ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); return isConnected; } }
here isInternetConnected function return a Boolean value of network state.
now you can call this function to get internet connectivity like
if (!InternetConnection.isInternetConnected(getApplicationContext())) { Toast.makeText(getApplicationContext(), "Please Check your internet connection.", Toast.LENGTH_SHORT).show(); return; } //Download or get some information from internet.
but sometimes we required some stuff that need network change state without any manual call. so to do this we have to create a broadcast receiver class where we handle the changes in network.
public class NetworkChangeReceiver extends BroadcastReceiver { @Override public void onReceive(final Context mContext, final Intent intent) { if (InternetConnection.isInternetConnected(mContext)) { //here you can get information from internet } } }
Once we define our BroadcastReceiver, we need to define the same in AndroidManifest.xml file. Add following to your manifest file.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Jitendra Negi
Jitendra is an Android application developer, specializing in native Android apps. He knows a lot about architecture, communications, jni material design and a lot of other things.