How to check if the Internet connection (Wifi/Mobi

2019-09-01 05:37发布

How to check if the internet connection is Enabled in Android? Like if the LOCATION SERVICE is disabled we use the technique

Location myLocation = locationmanager.getLastKnownLocation(provider);
if(myLocation == null){
      Show the AlertDialog.
}else{
do this.
}

Like this, how do i check if the Internet connection is Enabled/Disabled.

2条回答
老娘就宠你
2楼-- · 2019-09-01 05:58

You can use the following method:

ConnectivityManager conectivtyManager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);  
if (conectivtyManager.getActiveNetworkInfo() != null  
    && conectivtyManager.getActiveNetworkInfo().isAvailable()  
    && conectivtyManager.getActiveNetworkInfo().isConnected()) {  
    isConnected = true;  
} else {  
    isConnected= false;  
}  

Hope it helps!

查看更多
Deceive 欺骗
3楼-- · 2019-09-01 06:08

For wifi:

ConnectivityManager mgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = mgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
connected = networkInfo != null && networkInfo.isConnected();

For Mobile:

ConnectivityManager mgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = mgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
connected = networkInfo != null && networkInfo.isConnected();
查看更多
登录 后发表回答