1

So I just implemented a checking connectivity method, but should I do this for every activity? Is there a simpler way to continually check for connectivity?

public static boolean isNetworkAvailable(Context context) {

    ConnectivityManager cm =
            (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();

    boolean isConnected = activeNetwork != null &&
            activeNetwork.isConnectedOrConnecting();

    return isConnected;
}
James Jones
  • 572
  • 1
  • 6
  • 17
  • show us the code of your method – dumazy May 03 '15 at 19:08
  • 1
    You should check connectivity every time you actually need it. Every time before you perform a request or anything similar. There is no way around that. If you fail to perform a check you app may crash or start behaving weird. Both don't make for a good user experience. – Xaver Kapeller May 03 '15 at 19:49

5 Answers5

3

First create a ConnectivityChangeReceiver like the following:

public class ConnectivityChangeReceiver extends BroadcastReceiver {

    private OnConnectivityChangedListener listener;

    public ConnectivityChangeReceiver(OnConnectivityChangedListener listener) {
        this.listener = listener;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager connectivityManager = (ConnectivityManager) 
                context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        boolean isConnected = activeNetInfo != null && activeNetInfo.isConnectedOrConnecting();  
        listener.onConnectivityChanged(isConnected);
    }

    public interface OnConnectivityChangedListener {
        void onConnectivityChanged(boolean isConnected);
    }
}

Then create a BaseActivity which extends all of your activites:

public class BaseActivity extends Activity implements OnConnectivityChangedListener {

    private ConnectivityChangeReceiver connectivityChangeReceiver;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        connectivityChangeReceiver = new ConnectivityChangeReceiver(this);
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        registerReceiver(connectivityChangeReceiver, filter);
    }

    @Override
    public void onConnectivityChanged(boolean isConnected) {
        // TODO handle connectivity change
    }

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

(If you don't want a BaseActivity, you can implement OnConnectivityChangedListener in all of your activities. But in that case you have to register the receiver in all of your Activity.)

Zsolt Mester
  • 1,053
  • 9
  • 14
1

You should check before every request to the internet! The user can terminate the connection at any given time... even while your Activity is running.

I suggest you make an Utils class and put this method inside and make it public static so you can access it from everywhere within the Application.

Bojan Kseneman
  • 15,488
  • 2
  • 54
  • 59
1

You can check this out: This is service that will continuously check the connection. This will be the proper way to do it

`private void installListener() {

    if (broadcastReceiver == null) {

        broadcastReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {

                Bundle extras = intent.getExtras();

                NetworkInfo info = (NetworkInfo) extras
                        .getParcelable("networkInfo");

                State state = info.getState();
                Log.d("InternalBroadcastReceiver", info.toString() + " "
                        + state.toString());

                if (state == State.CONNECTED) {

                    onNetworkUp();

                } else {

                    onNetworkDown();

                }

            }
        };

        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(broadcastReceiver, intentFilter);
    }
}`

Look on this link: Android service to check internet connectivity?

Community
  • 1
  • 1
Aviad
  • 1,539
  • 1
  • 9
  • 24
1

Create some sort of util class, for example ConnectionUtils.

Add a public static method to that class and add a Context object to the parameters. For example:

public static boolean isNetworkAvailable(Context context) {

    ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

    return isConnected;
}

Then in your Activity just call ConnectionUtils.isNetworkAvailable(this) to know if you're connected.

It would even be better to create some sort of base Activity that you extend with this method in it.

public abstract class BaseActivity extends Activity {

    protected boolean isConnected() {
         return ConnectionUtils.isNetworkAvailable(this);
    }
}

And then let all your Activities extend BaseActivity instead of Activity

dumazy
  • 13,857
  • 12
  • 66
  • 113
0

I say it is better to check before every request. It might happen that the connection got broken in between. So its not wise to rely on a check sometime earlier

Msk
  • 857
  • 9
  • 16