I have a problem with checking internet connection in android at runtime. I use some different methods to check internet connection but i don't know which one is better . because each of them have some problems .
Method 1 check internet connection by pinging Google :
Runtime runtime = Runtime.getRuntime();
try {
Process mIpAddressProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int mExitValue = mIpAddressProcess.waitFor();
return mExitValue == 0;
} catch (InterruptedException | IOException ignore) {
ignore.printStackTrace();
}
Method 2 check internet connection by ConnectivityManager :
public boolean checkNetwork() {
ConnectivityManager internetManager = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = internetManager.getActiveNetworkInfo();
return (networkInfo != null && networkInfo.isConnected() && networkInfo.isAvailable() && networkInfo.isConnectedOrConnecting());
}
I use method 1 inside an async task, but it doesn't work correctly sometimes and slow down the app, and Method 2 (ConnectivityManager) doesn't check internet connection , it checks only network connection !
I'm using broadcast to check the connection every time. Create a class for connection info.
Apply code into your Activity:
Register broadcast in your activity's
onCreate()
method:Don't forget to unregistered/register on Activity cycle: