android.net.ConnectivityManager主要用于管理与网络连接相关的操作。
需要访问网络,首先需要添加权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
示例代码如下:
需要访问网络,首先需要添加权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
示例代码如下:
protected
void testNetwork(){
ConnectivityManager cm = (ConnectivityManager) this.getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if(networkInfo.isAvailable()){
Log.i(TAG, "network available");
} else{
Log.i(TAG , "network not available");
}
if(State.CONNECTED == cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState()){
Log.i(TAG , "gprs is connected");
}
if(State.CONNECTED == cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState()){
Log.i(TAG, "wifi is connected");
}
}
ConnectivityManager cm = (ConnectivityManager) this.getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if(networkInfo.isAvailable()){
Log.i(TAG, "network available");
} else{
Log.i(TAG , "network not available");
}
if(State.CONNECTED == cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState()){
Log.i(TAG , "gprs is connected");
}
if(State.CONNECTED == cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState()){
Log.i(TAG, "wifi is connected");
}
}
转载于:https://blog.51cto.com/mmqzlj/741805