Check Network Using BroadCastReceiver

Hello friends,

Hope you already see this example in lot of websites and blogs. I'm also doing these, because hope my example might be easy and understandable.

Let's go.

Create the class:


public class ConnectivityReceiver extends BroadcastReceiver {

    public static ConnectivityReceiverListener connectivityReceiverListener;

    public ConnectivityReceiver() {

    public void onReceive(Context context, Intent arg1) {
        ConnectivityManager cm = (ConnectivityManager) context
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean isConnected = activeNetwork != null
                && activeNetwork.isConnectedOrConnecting();

        if (connectivityReceiverListener != null) {

    public static boolean isConnected() {
                cm = (ConnectivityManager) ShukranApplication.getInstance().getApplicationContext()
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        return activeNetwork != null
                && activeNetwork.isConnectedOrConnecting();

    public interface ConnectivityReceiverListener {
        void onNetworkConnectionChanged(boolean isConnected);

In AndroidManifest.xml

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

then don't forget to add the receiver class.
        <action android:name="" />

Then In your application class,

public class MyApplication extends Application{
    private static MyApplication mInstance;

    public void onCreate() {
        mInstance = this;

    public static synchronized MyApplication getInstance() {
        return mInstance;

    public void setConnectivityListener(ConnectivityReceiver.ConnectivityReceiverListener listener) {
        ConnectivityReceiver.connectivityReceiverListener = listener;

This will be the final step, In anyother activity or fragment, Just call like that.

public class MyActivity extends AppCompatActivity
        implements ConnectivityReceiver.ConnectivityReceiverListener{
    public void onNetworkConnectionChanged(boolean isConnected) {


In events or directly to call,

//if true internet connected


Popular posts from this blog

Clear the app data programmatically in android

convert an integer to a string in java

Print the large string values in android log cat.