如何检查Android中的互联网连接是否已启用?就像LOCATION SERVICE被禁用一样,我们使用技术
Location myLocation = locationmanager.getLastKnownLocation(provider);
if(myLocation == null){
Show the AlertDialog.
}else{
do this.
}
像这样,我如何检查互联网连接是否已启用/已禁用。
答案 0 :(得分:2)
对于wifi:
ConnectivityManager mgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = mgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
connected = networkInfo != null && networkInfo.isConnected();
对于手机:
ConnectivityManager mgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = mgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
connected = networkInfo != null && networkInfo.isConnected();
答案 1 :(得分:2)
您可以使用以下方法:
ConnectivityManager conectivtyManager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
if (conectivtyManager.getActiveNetworkInfo() != null
&& conectivtyManager.getActiveNetworkInfo().isAvailable()
&& conectivtyManager.getActiveNetworkInfo().isConnected()) {
isConnected = true;
} else {
isConnected= false;
}
希望它有所帮助!