[RK3288][Android6.0] WiFi之与ConnectivityService的交互

Platform: Rockchip
OS: Android 6.0
Kernel: 3.10.92

在Wifi的整个过程中,有个函数一直会被调用到: setNetworkDetailedState(),它是用来和系统的ConnectivityService关联的,作用是为了告知系统当前wifi的状态,因为系统里存在多个网络,如有线网,数据上网等,像平常我们使用PC的时候,当有线网和wifi同时连着的时候,会优先选择wifi,Android系统的机制也是类似的。
因此wifi子模块通过setNetworkDetailedState()来告知系统当前连接状态以决定是否需要切换网络,而且同一时间只能有一个网络工作。

当断开wifi时,会调用
handleNetworkDisconnect -> setNetworkDetailedState(DetailedState.DISCONNECTED)
这时参数是DetailedState.DISCONNECTED

WifiStateMachine.java

private boolean setNetworkDetailedState(NetworkInfo.DetailedState state) 
{
    //新旧状态不一致时,要重新设置
    if (state != mNetworkInfo.getDetailedState()) {
        //设置新的状态
        mNetworkInfo.setDetailedState(state, null, mWifiInfo.getSSID());
        if (mNetworkAgent != null) {
            //和ConnectivityService通信的关键部分,会把更新的mNetworkInfo信息发过去
            mNetworkAgent.sendNetworkInfo(mNetworkInfo);
        }
        //广播网络状态变化: WifiManager.NETWORK_STATE_CHANGED_ACTION
        sendNetworkStateChangeBroadcast(null);
        return true;
    }
    return false;
}
public void sendNetworkInfo(NetworkInfo networkInfo) {
    queueOrSendMessage(EVENT_NETWORK_INFO_CHANGED, new NetworkInfo(networkInfo));
}

消息最终被ConnectivityService中的NetworkStateTrackerHandler处理

public void handleMessage(Message msg) {
    case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
        NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
        info = (NetworkInfo) msg.obj;
        updateNetworkInfo(nai, info);
        break;
    }
}

updateNetworkInfo -> networkAgent.asyncChannel.disconnect -> handleMessage -> handleAsyncChannelDisconnected

private void handleAsyncChannelDisconnected(Message msg) 
    // Remove all previously satisfied requests.
    for (int i = 0; i < nai.networkRequests.size(); i++) {
        NetworkRequest request = nai.networkRequests.valueAt(i);
        NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
        //移除当前要断开的网络
        if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
            mNetworkForRequestId.remove(request.requestId);
            //系统的连接的优先级是通过score来评判的,更新score
            sendUpdatedScoreToFactories(request, 0);
        }
    }
}

参考:
Framework中的连接管理机制(原)

你可能感兴趣的:(子类__WiFi)