androidandroid-fragmentsandroid-connectivitymanager

What will be the context for CONNECTIVITY_SERVICE in Fragment?


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;
    }
}

Solution

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

    getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);