需要访问网络,首先需要添加权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
示例代码如下:
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");
}
}