I tried the user approach : 3156908 , but he continued to destroy my application when the Internet connection was disconnected. It turns out that there was a logical error in his code, so I used connectivityManager.getActiveNetworkInfo() != null to check the network details. If the device is connected to a network or is in the process of connecting to a network, use isConnectedOrConnecting()
In your AndroidManifest.xml file add the following
<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(); }
You can then call the checkInternetConnection method in your onViewCreated or your onCreate activity onCreate .
Note I strongly recommend that you check the code when it is connected to Wi-Fi, mobile data, and flight mode.
source share