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 . b
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.
}
}
}