Android_NetworkInfo以及判断手机是否联网
描述了当前网络 Mobile和Wifi的状态。
有2个内部类 NetworkInfo.DetailedState(精确的网络状态)和 NetworInfo.State(粗略的网路状态)
Detailed state |
Coarse-grained state |
IDLE |
DISCONNECTED |
SCANNING |
CONNECTING |
CONNECTING |
CONNECTING |
AUTHENTICATING |
CONNECTING |
CONNECTED | |
DISCONNECTING |
DISCONNECTING |
DISCONNECTED |
DISCONNECTED |
UNAVAILABLE |
DISCONNECTED |
FAILED |
DISCONNECTED |
里面几个常用函数
isAvailable() isConnected() getDetailedState() getState() getExtrInfo()
getType() 获取当前网络的类型mobile or Wi-Fi
getTypeName() 获取当前网络的类型名 “WIFI” or “MOBILE”
ConnectivityManager
用于查询网络连接状态,当网络状态发生改变时通知应用。通过调用Context.getSystemService(Context.CONNECTIVITY_SERVICE)。主要功能:
1. 监视网络(Wi-Fi,GPRS,UMTS,etc)的连接
2. 网络状态发生改变时发送广播
3. 网络丢失时尝试转移的别的网络
4. 提供API
主要函数介绍
1. NetworkInfo getActiveNetworkInfo() 获取可用网络
2. NetworkInfo[] getAllNetworkInfo 获取所有可用网络
3. NetworkInfo getNetworkInfo(int networkType) 获取固定网络信息
4. isNetworkTypeValid(int networkType)
Android判断当前网络状态是否连接函数
Public static Boolean isNetworkConnected(Context context) { ConnectivityManager manager = (ConnectivityManager) context .getApplicationContext().getSystemService( Context.CONNECTIVITY_SERVICE); if (manager == null) { return false; } NetworkInfo networkinfo = manager.getActiveNetworkInfo(); if (networkinfo == null || !networkinfo.isAvailable()) { return false; } return true; }
···
···