Checking the Networking Connectivity using BroadcastReceiver in Android

Nandagopal T picture Nandagopal T · May 30, 2011 · Viewed 14.4k times · Source

I am using the BroadcastReceiver to check the network connectivity while my app is running.I have binded the BroadcastReceiver with the Activity inorder to bring few controls like AlertDialog while the connectivity goes down. but now i don't want to restrict this receiver to a particular activity instead i want to make this to be applied for my whole app(All Activities). So what way should i have to proceed to get that done...

This is the code that i have used.Please let me know whether my code reaches the standard and please correct me if have gone somewhere wrong.

package com.xx.mobile;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;


public class CheckforConnectivity extends Activity {
private static final String LOG_TAG = CheckforConnectivity.class.getSimpleName();
static final String ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
private boolean mActiveNetState = false;
private boolean mMobileNetState = false;
private boolean mStatus = false;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    IntentFilter filter = new IntentFilter(ACTION);
    this.registerReceiver(ConnectivityCheckReceiver, filter);
}

@Override
protected void onDestroy(){
    super.onDestroy();
    unregisterReceiver(ConnectivityCheckReceiver);
}



private final BroadcastReceiver mConnectivityCheckReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
        String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
                boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);
                    NetworkInfo currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
        NetworkInfo otherNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);
        Log.i(TAG, "Status : " + noConnectivity + ", Reason :" + reason + ", FailOver :" + isFailover + ", Current Network Info : " + currentNetworkInfo + ", OtherNetwork Info :" + otherNetworkInfo);

        mStatus = noConnectivity;
        Log.d(TAG, "Status :" + mStatus);

        if(mStatus){
        AlertDialog.Builder builder = new AlertDialog.Builder(NotifySMSReceived.this);
        builder.setMessage("Connection is not Available !");
        builder.setTitle("Info");
        builder.setPositiveButton("Ok", new DialogInterface.OnClickListener(){

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                dialog.dismiss();

            }

        });
        AlertDialog alert = builder.create();
        alert.show();
    }
    else {

            AlertDialog.Builder builder = new AlertDialog.Builder(NotifySMSReceived.this);
            builder.setMessage("Connection is Available !");
            builder.setTitle("Info");
            builder.setPositiveButton("Ok", new DialogInterface.OnClickListener(){

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    dialog.dismiss();

                }

            });
            AlertDialog alert = builder.create();
            alert.show();
    }



    }
};
}

Any sort of help is highly appreciated.

Thanks

Answer

Flo picture Flo · May 30, 2011

I think you got 2 options.

First option

First you should register your receiver not with code but within the manifest file. By this way it is registered automatically for your application. Within you receiver you have to store the current state of the network somewhere centrally perhaps in a custom Application class or a singleton class.

Implement some kind of observer pattern so that your activities could register themselves to your custom Application class which holds the network state. The Application class then informs every registered activity about the change of the network state.

You activity class register and unregister to/from the Application class in onCreate() and onDestroy() (better would be onResume() and onPause()) so they get only informed about network changes when they're visible.

Second option

Another option would be to stick to you current code and hold the reference of the Broadcast receiver somewhere centrally, again a custom Application class would do the job.

So your activities know where to find the receiver for registering and unregistering. But be aware that you have to find a place where you initiate the receiver. Also keep in mind that you have to handle the case where you application might be closed by Android because of low memory and restarted later, you'll then have to recreate your receiver.