I tried the approach of user:3156908 but it kept crashing my app when the internet connection was off. Turns out there was a logical error on his code so i used the connectivityManager.getActiveNetworkInfo() != null
to check for network details. In case the device is connected to the network or it is in the process of connecting to the network use the isConnectedOrConnecting()
In your AndroidManifest.xml file add the following
<!-- Internet Permissions -->
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Create a method called checkInternetConnection
in your fragment class or Activity class and add the following lines of code.
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private boolean checkInternetConnection(){
ConnectivityManager connectivityManager = (ConnectivityManager) mcontext.getSystemService(mcontext.CONNECTIVITY_SERVICE);
return connectivityManager.getActiveNetworkInfo() != null
&& connectivityManager.getActiveNetworkInfo().isConnectedOrConnecting();
}
Then you can call the checkInternetConnection
in your fragment's onViewCreated
method or your activity's onCreate
method.
Note
I would strongly advise you to test it the code when its connected to wifi, mobile data and airplane mode.