Android - How to Check Internet Connection

The above methods work when you are connected to a Wi-Fi source or via cell phone data packs. But in case of Wi-Fi connection there are cases when you are further asked to Sign-In like in Cafe. So in that case your application will fail as you are connected to Wi-Fi source but not with the Internet.
In Manifest
Add this code in manifest file
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Create New Class Name : DetectInternetConnection
Replace This Code
public class DetectInternetConnection {
  public static boolean checkInternetConnection(Context context){

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

      if (con_manager.getActiveNetworkInfo() != null  && 
          con_manager.getActiveNetworkInfo().isAvailable()
          && con_manager.getActiveNetworkInfo().isConnected()) {
          return true;
      } else {
          return false;
      }
    }
}
How to Apply Code  : Example in onResume

@Overrideprotected void onResume() {
    super.onResume();
    if (!DetectInternetConnection.checkInternetConnection(getApplicationContext())) {
        showNotificationNoInternetDialog();
    }
}
SHARE

About Unknown

    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment