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 !
You can use below code to check whether network connection is available or not.
public class NetworkConnection {
public Context context;
public NetworkConnection(Context applicationContext) {
this.context=applicationContext;
}
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
}
public class MainActivity extends AppCompatActivity {
NetworkConnection nt_check;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
nt_check=new NetworkConnection(context);
if(nt_check.isOnline()) {
// do logic
} else {
// show message network is not available.
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With