2

What will be the context for CONNECTIVITY_SERVICE in a Fragment? I have checked getActivity also but it is giving an error.

public boolean isOnline() {
    ConnectivityManager connectionManager = (ConnectivityManager) 
        getSystemService(Context.CONNECTIVITY_SERVICE);
    try {
        if (connectionManager.getActiveNetworkInfo().isConnected()) {
            Log.d("ConStatus", "Data Connection On");
            return true;
        } else {
            Log.d("ConStatus", "Data Connection off");
            return false;
        }
    } catch (NullPointerException e) {
        Log.i("ConStatus", "No Active Connection");
        return false;
    }
}
Matt N.
  • 53
  • 1
  • 10
user1744952
  • 508
  • 1
  • 3
  • 15

2 Answers2

4

getSystemService() is a method on Context. A Fragment would call it using getActivity():

getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
0

I faced a similar problem when trying to implement a Google map offline tile provider within a fragment (based on 0ne_Up's answer here). I solved it by using the following:

private ConnectivityManager connectivityManager;
...
connectivityManager = (ConnectivityManager) getActivity().
    getSystemService( getActivity().CONNECTIVITY_SERVICE );
Dharman
  • 30,962
  • 25
  • 85
  • 135
Matt N.
  • 53
  • 1
  • 10