http://blog.csdn.net/andyhuabing/article/details/7790092
在当前网络成为必不可少的条件时,Android系统也集成的wifi,bluetooth,eth,cablemodem等等,为了将其它网络加入进来,大致浏览一下网络管理的相关分析,重点看了wifi的管理,还是绕了很多弯弯的。
public static final int TYPE_MOBILE = 0;
public static final int TYPE_WIFI = 1;
public static final int TYPE_MOBILE_MMS = 2;
public static final int TYPE_MOBILE_SUPL = 3;
public static final int TYPE_MOBILE_DUN = 4;
public static final int TYPE_MOBILE_HIPRI = 5;
public static final int TYPE_WIMAX = 6;
public static final int TYPE_PPPOE = 7;
public static final int TYPE_ETHERNET = 8;
public static final int TYPE_CABLEMODEM = 9;
public static final int DEFAULT_NETWORK_PREFERENCE = TYPE_WIFI;
设置了默认的网络连接是TYPE_WIFI
而android系统中对众多的网络类型进行管理其整个流程是怎样的呢?下面就来分析一下吧。
系统中对网络的判断和选在是在 ConnectivityService.java 这个服务中来处理的,在系统启动的时候会启动这个系统服务,
而在系统启动完毕后,ConnectivityService在系统启动的时候就启动了。
用户操作的类是 ConnectivityManager.java 通过aidl访问 ConnectivityService.java提供的服务。
public class ConnectivityService extends IConnectivityManager.Stub
看定义就相当明确了。。
1、网络服务启动
SystemServer启动 ConnectivityService,ConnectivityService 服务中启动对网络的监视器
在SystemServer的run()函数中,启动 ConnectivityService 的代码:
- try {
- Slog.i(TAG, "Connectivity Service");
- connectivity = ConnectivityService.getInstance(context);
- ServiceManager.addService(Context.CONNECTIVITY_SERVICE, connectivity);
- } catch (Throwable e) {
- Slog.e(TAG, "Failure starting Connectivity Service", e);
- }
- f (connectivityF != null) connectivityF.systemReady();
2、增加定义网络类型
framework/base/core/res/res/values/config.xml中定义了网络的类型
类型定义如下:
<!-- This string array should be overridden by the device to present a list of network
attributes. This is used by the connectivity manager to decide which networks can coexist
based on the hardware -->
<!-- An Array of "[Connection name],[ConnectivityManager connection type],
[associated radio-type],[priority] -->
<string-array translatable="false" name="networkAttributes">
<item>"wifi,1,1,2"</item>
<item>"mobile,0,0,3"</item>
<item>"mobile_mms,2,0,4"</item>
<item>"mobile_supl,3,0,4"</item>
<item>"mobile_hipri,5,0,5"</item>
<item>"pppoe,7,7,1"</item>
<item>"ethernet,8,8,0"</item>
<item>"cablemodem,9,9,0"</item>
</string-array>
!!!!! 参考 NetworkAttributes 类定义即明白什么意思了
<!-- This string array should be overridden by the device to present a list of radio
attributes. This is used by the connectivity manager to decide which networks can coexist
based on the hardware -->
<!-- An Array of "[ConnectivityManager connectionType],
[# simultaneous connection types]" -->
<string-array translatable="false" name="radioAttributes">
<item>"9,1"</item>
<item>"8,1"</item>
<item>"7,1"</item>
<item>"1,1"</item>
<item>"0,1"</item>
</string-array>
!!!! 参考 RadioAttributes 类定义即明白什么意思了
这里代表什么含义呢?在 ConnectivityService内部,定义了两个类用于解析xml文件中内容。
- private static class NetworkAttributes {
- /**
- * Class for holding settings read from resources.
- */
- public String mName;
- public int mType;
- public int mRadio;
- public int mPriority;
- public NetworkInfo.State mLastState;
- public NetworkAttributes(String init) {
- String fragments[] = init.split(",");
- mName = fragments[0].toLowerCase();
- mType = Integer.parseInt(fragments[1]);
- mRadio = Integer.parseInt(fragments[2]);
- mPriority = Integer.parseInt(fragments[3]);
- mLastState = NetworkInfo.State.UNKNOWN;
- }
- public boolean isDefault() {
- return (mType == mRadio);
- }
- }
- private static class RadioAttributes {
- public int mSimultaneity;
- public int mType;
- public RadioAttributes(String init) {
- String fragments[] = init.split(",");
- mType = Integer.parseInt(fragments[0]);
- mSimultaneity = Integer.parseInt(fragments[1]);
- }
- }
网络有优先级之分,优先级高的先被执行,这是通过如下代码进行分配的:
- // high priority first
- mPriorityList = new int[mNetworksDefined];
- {
- int insertionPoint = mNetworksDefined-1;
- int currentLowest = 0;
- int nextLowest = 0;
- while (insertionPoint > -1) {
- for (NetworkAttributes na : mNetAttributes) {
- if (na == null) continue;
- if (na.mPriority < currentLowest) continue;
- if (na.mPriority > currentLowest) {
- if (na.mPriority < nextLowest || nextLowest == 0) {
- nextLowest = na.mPriority;
- }
- continue;
- }
- mPriorityList[insertionPoint--] = na.mType;
- }
- currentLowest = nextLowest;
- nextLowest = 0;
- }
- }
其中,TYPE_MOBILE_HIPRI的优先级最高,其次为TYPE_MOBILE_MMS,TYPE_MOBILE_SUPL,TYPE_MOBILE_DUN,
优先级最低的为TYPE_WIFI,TYPE_MOBILE。TYPE_WIFI,TYPE_MOBILE两个网络类型中,TYPE_WIFI大于TYPE_MOBILE的优先级
在打开wifi的连接后,mobile网络会被关闭。wifi网络连接关闭后,mobile网络会重新连接.
在处理网络连接的Handler的代码中有处理:
- private void handleConnect(NetworkInfo info) {
- int type = info.getType();
- // snapshot isFailover, because sendConnectedBroadcast() resets it
- boolean isFailover = info.isFailover();
- NetworkStateTracker thisNet = mNetTrackers[type];
- // if this is a default net and other default is running
- // kill the one not preferred
- if (mNetAttributes[type].isDefault()) {
- if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
- if ((type != mNetworkPreference &&
- mNetAttributes[mActiveDefaultNetwork].mPriority >
- mNetAttributes[type].mPriority) ||
- mNetworkPreference == mActiveDefaultNetwork) {
- <span style="color:#3366FF;"> // don't accept this one
- if (DBG) Slog.v(TAG, "Not broadcasting CONNECT_ACTION " +
- "to torn down network " + info.getTypeName());
- teardown(thisNet);</span>
- return;
- } else {
- <span style="color:#3333FF;"> // tear down the other
- NetworkStateTracker otherNet =
- mNetTrackers[mActiveDefaultNetwork];
- if (DBG) Slog.v(TAG, "Policy requires " +
- otherNet.getNetworkInfo().getTypeName() +
- " teardown");
- if (!teardown(otherNet)) {
- Slog.e(TAG, "Network declined teardown request");
- return;
- }
- if (isFailover) {
- otherNet.releaseWakeLock();
- }</span>
- }
- }
- mActiveDefaultNetwork = type;
- // this will cause us to come up initially as unconnected and switching
- // to connected after our normal pause unless somebody reports us as reall
- // disconnected
- mDefaultInetConditionPublished = 0;
- mDefaultConnectionSequence++;
- mInetConditionChangeInFlight = false;
- // Don't do this - if we never sign in stay, grey
- //reportNetworkCondition(mActiveDefaultNetwork, 100);
- }
- thisNet.setTeardownRequested(false);
- thisNet.updateNetworkSettings();
- handleConnectivityChange(type);
- sendConnectedBroadcast(info);
- }
因此请注意,由于WIFI优先级高于ETH网络,如果wifi被开启,可以eth就会被关闭掉,而如果我们想在
这两者同时存在,那么在调用teardown(NetworkStateTracker)函数前进行判定即可。
2、启个各类网络监控器服务代码,这里以wifi为例
在ConnectivityService的构造函数中启动网络监视器的代码
- /*
- * Create the network state trackers for Wi-Fi and mobile
- * data. Maybe this could be done with a factory class,
- * but it's not clear that it's worth it, given that
- * the number of different network types is not going
- * to change very often.
- */
- boolean noMobileData = !getMobileDataEnabled();
- for (int netType : mPriorityList) {
- switch (mNetAttributes[netType].mRadio) {
- case ConnectivityManager.TYPE_WIFI:
- if (DBG) Slog.v(TAG, "Starting Wifi Service.");
- WifiStateTracker wst = new WifiStateTracker(context, mHandler);
- WifiService wifiService = new WifiService(context, wst);
- ServiceManager.addService(Context.WIFI_SERVICE, wifiService);
- wifiService.startWifi();
- mNetTrackers[ConnectivityManager.TYPE_WIFI] = wst;
- wst.startMonitoring();
- break;
在settings中可以设置网络连接,比如打开wifi,打开bluetooth,设置apn的连接等等,在设置完成后,设置的消息会存在一个数据库中保存,并发送系统消息来广播网络设置的变化。
在网络监视器中捕捉了settings中发出的相应的网络广播信息,网络监视器中注册了settings中网络变化的信息,有变化会做相应的处理,并将处理的结果存储在NetworkInfo类的一个对象中,在ConnectivityService中通过
public NetworkInfo getNetworkInfo(int networkType)方法可以得知当前networkType类型网络的连接情况。
3、 应用监控
在app中,我们可以通过 ConnectivityManager 来获取当前的网络信息,并能指定当前程序需要的网络类型:
ConnectivityManager mCnn = context.getSystemService(context.CONNECTIVITY_SERVICE);
NetworkInfo mNetinfo = mCnn.getActiveNetworkInfo();
mCnn.setNetworkPreference(int preference);//设定首选网络类型。
假如没有设定,网络类型为系统默认。在wifi,3G网络同时存在的情况下,系统会默认的调用wifi网络,加载wifi的驱动,走wifi网络。
4、下面详细分析一下wifi网络信息
wifi 图示层次:
ConnectivityService 的构造函数会将 WifiService 添加到 ServiceManager 中,使之需要服务者可以访问。
mWifiStateTracker = new WifiStateTracker(context, handler);
WifiService wifiService = new WifiService(context, mWifiStateTracker);
ServiceManager.addService(Context.WIFI_SERVICE, wifiService);
WifiStateTracker 会创建 WifiMonitor 接收来自底层的事件,WifiService 和 WifiMonitor 是整个模块的核心。
WifiService 负责启动关闭 wpa_supplicant、启动关闭 WifiMonitor 监视线程
和把命令下发给 wpa_supplicant,而 WifiMonitor 则负责从 wpa_supplicant 接收事件通知。
连接 AP:
1. 使能 WIFI
WirelessSettings 在初始化的时候配置了由 WifiEnabler 来处理 Wifi 按钮,
当用户按下 Wifi 按钮后, Android 会调用 WifiEnabler 的 onPreferenceChange,
再由 WifiEnabler 调用 WifiManager 的 setWifiEnabled 接口函数,通过 AIDL,实际调用的是 WifiService 的
setWifiEnabled 函数,WifiService 接着向自身发送一条 MESSAGE_ENABLE_WIFI 消息,
在处理该消息的代码中做真正的使能工作:
- @Override
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case MESSAGE_ENABLE_WIFI:
- setWifiEnabledBlocking(true, msg.arg1 == 1, msg.arg2);
- if (mWifiWatchdogService == null) {
- mWifiWatchdogService = new WifiWatchdogService(mContext, mWifiStateTracker);
- }
- sWakeLock.release();
- break;
首先装载 WIFI 内核模块(该模块的位置硬编码为"/system/lib/modules/wlan.ko" ), 然后启动 wpa_supplicant
(配置文件硬编码为"/data/misc/wifi/wpa_supplicant.conf") 再通过 WifiStateTracker 来启动
WifiMonitor 中的监视线程。
- private boolean setWifiEnabledBlocking(boolean enable, boolean persist, int uid) {
- ...
- setWifiEnabledState(enable ? WIFI_STATE_ENABLING : WIFI_STATE_DISABLING, uid);
- if (enable) {
- if (!mWifiStateTracker.loadDriver()) {
- Slog.e(TAG, "Failed to load Wi-Fi driver.");
- setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
- return false;
- }
- if (!mWifiStateTracker.startSupplicant()) {
- mWifiStateTracker.unloadDriver();
- Slog.e(TAG, "Failed to start supplicant daemon.");
- setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
- return false;
- }
- registerForBroadcasts();
- mWifiStateTracker.startEventLoop();
- }
当使能成功后,会广播发送 WIFI_STATE_CHANGED_ACTION 这个 Intent 通知外界 WIFI 已经成功使能了
// Broadcast
final Intent intent = new Intent(WifiManager.WIFI_STATE_CHANGED_ACTION);
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
mContext.sendStickyBroadcast(intent);
WifiEnabler 创建的时候就会向 Android 注册接收
- /**
- * Registers to receive the necessary Wi-Fi broadcasts.
- */
- private void registerForWifiBroadcasts() {
- IntentFilter intentFilter = new IntentFilter();
- intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
- intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
- mContext.registerReceiver(mReceiver, intentFilter);
- }
WIFI_STATE_CHANGED_ACTION,因此它会收到该 Intent,从而开始扫描。
- /**
- * see {@link android.net.wifi.WifiManager#startScan()}
- */
- public void startScan(boolean forceActive) {
- enforceChangePermission();
- if (mWifiHandler == null) return;
- Message.obtain(mWifiHandler, MESSAGE_START_SCAN, forceActive ? 1 : 0, 0).sendToTarget();
- }
2. 查找 AP
扫描的入口函数是 WifiService 的 startScan,它其实也就是往 wpa_supplicant 发送 SCAN 命令。
- static jboolean android_net_wifi_scanCommand(JNIEnv* env, jobject clazz, jboolean forceActive)
- {
- jboolean result;
- // Ignore any error from setting the scan mode.
- // The scan will still work.
- if (forceActive && !sScanModeActive)
- doSetScanMode(true);
- result = doBooleanCommand("SCAN", "OK");
- if (forceActive && !sScanModeActive)
- doSetScanMode(sScanModeActive);
- return result;
- }
当 wpa_supplicant 处理完 SCAN 命令后,它会向控制通道发送事件通知扫描完成,从而wifi_wait_for_event 函数会接收到该事件,由此 WifiMonitor 中的 MonitorThread 会被执行来出来这个事件
- static jstring android_net_wifi_waitForEvent(JNIEnv* env, jobject clazz)
- {
- char buf[256];
- int nread = ::wifi_wait_for_event(buf, sizeof buf);
- if (nread > 0) {
- return env->NewStringUTF(buf);
- } else {
- return env->NewStringUTF(NULL);
- }
- }
- void handleEvent(int event, String remainder) {
- case SCAN_RESULTS:
- mWifiStateTracker.notifyScanResultsAvailable();
- break;
WifiStateTracker 则接着广播发送 SCAN_RESULTS_AVAILABLE_ACTION 这个 Intent
case EVENT_SCAN_RESULTS_AVAILABLE:
mContext.sendBroadcast(new Intent(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
WifiLayer 注册了接收 SCAN_RESULTS_AVAILABLE_ACTION 这个 Intent,所以它的相关
处理函数 handleScanResultsAvailable 会被调用,在该函数中,先会去拿到 SCAN 的结果
(最终是往 wpa_supplicant 发送 SCAN_RESULT 命令并读取返回值来实现的) ,
List<ScanResult> list = mWifiManager.getScanResults();
对每一个扫描返回的 AP,WifiLayer 会调用 WifiSettings 的 onAccessPointSetChanged 函数,
从而最终把该 AP 加到 GUI 显示列表中。
- public void onAccessPointSetChanged(AccessPointState ap, boolean added) {
- AccessPointPreference pref = mAps.get(ap);
- if (added) {
- if (pref == null) {
- pref = new AccessPointPreference(this, ap);
- mAps.put(ap, pref);
- } else {
- pref.setEnabled(true);
- }
- mApCategory.addPreference(pref);
- }
- }
3. 配置 AP 参数
当用户在 WifiSettings 界面上选择了一个 AP 后,会显示配置 AP 参数的一个对话框,
- public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference
- preference) {
- if (preference instanceof AccessPointPreference) {
- AccessPointState state=((AccessPointPreference)preference).getAccessPointState();
- showAccessPointDialog(state, AccessPointDialog.MODE_INFO);
- }
- }
4. 连接
当用户在 AcessPointDialog 中选择好加密方式和输入密钥之后,再点击连接按钮,Android就会去连接这个 AP。
- private void handleConnect() {
- String password = getEnteredPassword();
- if (!TextUtils.isEmpty(password)) {
- mState.setPassword(password);
- }
- mWifiLayer.connectToNetwork(mState);
- }
WifiLayer 会先检测这个 AP 是不是之前被配置过,这个是通过向 wpa_supplicant 发送LIST_NETWORK 命令并且比较返回值来实现的,
// Need WifiConfiguration for the AP
WifiConfiguration config = findConfiguredNetwork(state);
如果 wpa_supplicant 没有这个 AP 的配置信息则会向 wpa_supplicant 发送 ADD_NETWORK 命令来添加该 AP,
if (config == null) {
// Connecting for the first time, need to create it
config = addConfiguration(state,ADD_CONFIGURATION_ENABLE|ADD_CONFIGURATION_SAVE);
}
ADD_NETWORK 命 令 会 返 回 一 个 ID , WifiLayer 再 用 这 个 返 回 的 ID 作 为 参 数 向
wpa_supplicant 发送 ENABLE_NETWORK 命令,从而让 wpa_supplicant 去连接该 AP。
// Make sure that network is enabled, and disable others
mReenableApsOnNetworkStateChange = true;
if (!mWifiManager.enableNetwork(state.networkId, true)) {
Log.e(TAG, "Could not enable network ID " + state.networkId);
error(R.string.error_connecting);
return false;
}
5. 配置 IP 地址
当 wpa_supplicant 成功连接上 AP 之后,它会向控制通道发送事件通知连接上 AP 了,从而
wifi_wait_for_event 函数会接收到该事件,由此 WifiMonitor 中的 MonitorThread 会被执行来
出来这个事件,
void handleEvent(int event, String remainder) {
case CONNECTED:
handleNetworkStateChange(NetworkInfo.DetailedState.CONNECTED,remainder);
break;
WifiMonitor 再调用 WifiStateTracker 的 notifyStateChange,WifiStateTracker 则接着会往自身
发送 EVENT_DHCP_START 消息来启动 DHCP 去获取 IP 地址,
- private void handleConnectedState() {
- setPollTimer();
- mLastSignalLevel = -1;
- if (!mHaveIPAddress && !mObtainingIPAddress) {
- mObtainingIPAddress = true;
- mDhcpTarget.obtainMessage(EVENT_DHCP_START).sendToTarget();
- }
- }
然后再广播发送 NETWORK_STATE_CHANGED_ACTION 这个 Intent
case EVENT_NETWORK_STATE_CHANGED:
if (result.state != DetailedState.DISCONNECTED || !mDisconnectPending) {
intent = new Intent(WifiManager.NETWORK_STATE_CHANGED_ACTION);
intent.putExtra(WifiManager.EXTRA_NETWORK_INFO,mNetworkInfo);
if (result.BSSID != null)
intent.putExtra(WifiManager.EXTRA_BSSID, result.BSSID);
mContext.sendStickyBroadcast(intent);
}
break;
WifiLayer 注册了接收 NETWORK_STATE_CHANGED_ACTION 这个 Intent,所以它的相关处理函数 handleNetworkStateChanged 会被调用,
当 DHCP 拿到 IP 地址之后,会再发送 EVENT_DHCP_SUCCEEDED 消息,
- private class DhcpHandler extends Handler {
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case EVENT_DHCP_START:
- if (NetworkUtils.runDhcp(mInterfaceName, mDhcpInfo)) {
- event = EVENT_DHCP_SUCCEEDED;
- }
WifiLayer 处 理 EVENT_DHCP_SUCCEEDED 消息 , 会再次广播发送NETWORK_STATE_CHANGED_ACTION 这个 Intent,这次带上完整的 IP 地址信息。
- case EVENT_DHCP_SUCCEEDED:
- mWifiInfo.setIpAddress(mDhcpInfo.ipAddress);
- setDetailedState(DetailedState.CONNECTED);
- intent =new Intent(WifiManager.NETWORK_STATE_CHANGED_ACTION);
- intent.putExtra(WifiManager.EXTRA_NETWORK_INFO, mNetworkInfo);
- mContext.sendStickyBroadcast(intent);
- break;
至此为止,整个连接过程完成。