1. app调用wifiManager的connect方法
WifiManager WifiService WifiServiceImpl ConnectHelper ClientModeManager ClientModeImpl WifiNative SupplicantStaIfaceHal SupplicantStaNetworkHal App层 connect connectInternal framework层 connect (Binder调用) connect connectToNetwork connectNetwork connectNetwork ClientModeImpl设计了状态机,后面会单独研究这块 connectToNetwork (调到native层) native层 connectToNetwork (与hal层交互) hal层 select() (选定要连接的wifi) WifiManager WifiService WifiServiceImpl ConnectHelper ClientModeManager ClientModeImpl WifiNative SupplicantStaIfaceHal SupplicantStaNetworkHal
2.APP侧监听连接结果
2.1 应用层监听代码
cpp
private void listenConnectState() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
Log.d(TAG, "*************** networkState:" + networkInfo.getState());
assert networkInfo != null;
if (networkInfo.isConnected()) {
Log.d(TAG, "sucess------------");
} else if (networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Log.d(TAG, "disconnected------------");
}
}
};
mContext.registerReceiver(receiver, intentFilter);
}
2.2 重要接口概述:
- Client Mode(客户端模式):设备作为客户端连接到一个无线接入点(AP),进行互联网或局域网通信。然后clientMode的实现在ClientModeImpl中
- wifi回调事件都会进入ClientModeImpl::WifiNetworkAgentCallback
- Scan-Only Mode(仅扫描模式):设备在该模式下仅进行 Wi-Fi 网络扫描,并不进行实际的数据连接。这通常用于搜索附近的 Wi-Fi 网络或检查网络状态。scanOnly则实现在ScanOnlyModeImpl中
2.3 ClientModeImpl类的状态切换
- 简单的说: 就是app发起连接调用,按1描述的流程调用到ClientModeImpl, 然后再各个子状态之间跳转。比如下面的流程就是app发起wifi连接的流程,从DisconnectedState一步步变到L3ConnectedState。
APP ClientModeImpl DisconnectedState ConnectableState wifiNative L2ConnectingState L2ConnectedState WifiNetworkAgentCallback NetworkAgent ConnectivityManager L3ConnectedState APP侧调用wifiManager发起连接 收到CMD_CONNECT_NETWORK 调用connectToUserSelectNetwork 发送CMD_START_CONNECT 消息 处理 CMD_START_CONNECT 调用connectToNetwork connectToNetwork 切到L2Connecting 注册回调 new WifiNetworkAgentCallback new register() registerNetworkAgent() alt [注册ConnectivityManager- 的Binder] 根据回调进入不同的接口,发出不同的handelr消息 切到L3ConnectedState transitionTo(mL3ConnectedState) sendNetworkChangeBroadcast(DetailedState.CONNECTED) 发送广播,通知到APP 收到广播 alt [收到CMD_IP_CONFIGURATION_SUCCESSFUL] [收到WifiMonitor.NETWORK_CONNECTION_EVENT事件] APP ClientModeImpl DisconnectedState ConnectableState wifiNative L2ConnectingState L2ConnectedState WifiNetworkAgentCallback NetworkAgent ConnectivityManager L3ConnectedState