I need to detect whether internet connection is available and working fine in android. I need this condition check to call before i start any of my WebView Activities.
So far I have managed to implement the isAvailable() feature found in this answer: Class which check for connectivity
However, the above method fails in case when wifi is ON but ethernet plug is NOT connected. Some say using ping is a good idea. But I am not able to successfully implement this feature.
- How do I implement the ping feature in the code given in the link
- My android application uses Retrofit API for sending and receiving PHP contents. Can Retrofit help in checking for internet connectivity?
- Can you suggest any other simple and easy to implement method for checking Real-Time internet connectivity?
Code I have used from this link :-
Class name: AppStatus
import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.util.Log; public class AppStatus { private static AppStatus instance = new AppStatus(); static Context context; ConnectivityManager connectivityManager; NetworkInfo wifiInfo, mobileInfo; boolean connected = false; public static AppStatus getInstance(Context ctx) { context = ctx.getApplicationContext(); return instance; } public boolean isOnline() { try { connectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); connected = networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected(); return connected; } catch (Exception e) { System.out.println("CheckConnectivity Exception: " + e.getMessage()); Log.v("connectivity", e.toString()); } return connected;
}
This code helps in checking for internet connectivity but fails in the previously mentioned condition :-
if (AppStatus.getInstance(this).isOnline()) { Toast.makeText(this,"You are online!!!!",8000).show(); } else { Toast.makeText(this,"Internet Connection is required !",8000).show(); Log.v("Home", "############################You are not online!!!!"); finish(); }