ConnectivityManager主要管理和网络连接相关的操作,NetworkInfo类包含了对wifi和mobile两种网络模式连接的详细描述,通过其getState()方法获取的State对象则代表着连接成功与否等状态。
CONNECTED
Detailed state | Coarse-grained state |
IDLE |
DISCONNECTED |
SCANNING |
CONNECTING |
CONNECTING |
CONNECTING |
AUTHENTICATING |
CONNECTING |
CONNECTED |
|
DISCONNECTING |
DISCONNECTING |
DISCONNECTED |
DISCONNECTED |
UNAVAILABLE |
DISCONNECTED |
FAILED |
DISCONNECTED |
if(State.CONNECTED==state){
Log.i("TAG", "GPRS网络已连接");
}
state = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
if(State.CONNECTED==state){
Log.i("TAG“, "WIFI网络已连接");
}
- //判断网络是否可用
- public static boolean isNetworkAvaiable(Context context){
- ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
- NetworkInfo info = connectivityManager.getActiveNetworkInfo(); // 获取代表联网状态的NetWorkInfo对象
- return (info != null && info.isConnected());
- }
- //判断WIFI是否可用
- public static boolean isWifiActive(Context context){
- ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
- NetworkInfo[] info = connectivityManager.getAllNetworkInfo();
- if(info!=null){
- for(int i=0;i<info.length;i++){
- //
- if(info[i].getTypeName().equals(ConnectivityManager.TYPE_WIFI)&& info[i].isConnected())
- return true;
- }
- }
- return false;
- }
ConnectivityManager.TYPE_WIFI 表示wifi连接
ConnectivityManager.TYPE_MOBILE 表示3G连接
网络设置Intent:
new Intent(Android.provider.Settings.ACTION_WIRELESS_SETTINGS) // 跳转到无线网络设置界面
new Intent(Android.provider.Settings.ACTION_WIFI_SETTINGS) // 跳转到无线wifi网络设置界面
最后别忘了在mainifest文件中加上权限:
"<uses-permission Android:name="android.permission.ACCESS_NETWORK_STATE"/>"
更多Android相关信息见 Android 专题页面 http://www.linuxidc.com/topicnews.aspx?tid=11