Android9.0 Wifi开启流程

摘要:Android9.0里wifi的框架做了一些变动,包括wifi开启流程,前面与8.0差不多,到了WifiServiceImpl后面就有了很大变动,网上大都是总结的8.0的流程,然而Android10.0都出来了,所以这里我把9.0里Wifi开启流程梳理一遍。

总体代码路径可以就是这样:
WIfiEnabler->WifiManager->WifiService->WifiServiceImpl->WIfiStateMachinePrime->WIfiStateMachine->WifiNative

下面进入主题:
1、在wifisettings activity的onStart函数中,创建一个WifiEnabler对象,用于实现wifi开关功能
/packages/apps/Settings/src/com/android/settings/wifi/WifiSettings.java

    public void onStart() {
        super.onStart();

        // On/off switch is hidden for Setup Wizard (returns null)
        mWifiEnabler = createWifiEnabler();

        if (mIsRestricted) {
            restrictUi();
            return;
        }

        onWifiStateChanged(mWifiManager.getWifiState());
    }
    private WifiEnabler createWifiEnabler() {
        final SettingsActivity activity = (SettingsActivity) getActivity();
        return new WifiEnabler(activity, new SwitchBarController(activity.getSwitchBar()),
            mMetricsFeatureProvider);
    }

2、 WifiEnabler实现了SwitchWidgetController.OnSwitchChangeListener接口,所以重写了SwitchToggled方法。
WifiEnabler开关SwitchToggled中会调用WifiManager.setWifiEnabled方法。
/packages/apps/Settings/src/com/android/settings/wifi/WifiEnabler.java

    public boolean onSwitchToggled(boolean isChecked) {
        //Do nothing if called as a result of a state machine event
        if (mStateMachineEvent) {
            return true;
        }
        // Show toast message if Wi-Fi is not allowed in airplane mode
        if (isChecked && !WirelessUtils.isRadioAllowed(mContext, Settings.Global.RADIO_WIFI)) {
            Toast.makeText(mContext, R.string.wifi_in_airplane_mode, Toast.LENGTH_SHORT).show();
            // Reset switch to off. No infinite check/listener loop.
            mSwitchWidget.setChecked(false);
            return false;
        }

        if (isChecked) {
            mMetricsFeatureProvider.action(mContext, MetricsEvent.ACTION_WIFI_ON);
        } else {
            // Log if user was connected at the time of switching off.
            mMetricsFeatureProvider.action(mContext, MetricsEvent.ACTION_WIFI_OFF,
                    mConnected.get());
        }
        if (!mWifiManager.setWifiEnabled(isChecked)) {
            // Error
            mSwitchWidget.setEnabled(true);
            Toast.makeText(mContext, R.string.wifi_error, Toast.LENGTH_SHORT).show();
        }
        return true;
    }

3、WifiManager调用WifiService的方法。
/frameworks/base/wifi/java/android/net/wifi/WifiManager.java

    public boolean setWifiEnabled(boolean enabled) {
        try {
            return mService.setWifiEnabled(mContext.getOpPackageName(), enabled);
        } catch (RemoteException e) {
            throw e.rethrowFromSystemServer();
        }
    }

4、WiFiManager.aidl中写了setWifiEnabled()方法。
/frameworks/base/wifi/java/android/net/wifi/IWifiManager.aidl

    boolean setWifiEnabled(String packageName, boolean enable);

5、WifiServiceImpl中实现WifiManager的方法,在setWifiEnabled函数中向WifiStateMachinePrime发消息:CMD_WIFI_TOGGLED.
/frameworks/opt/net/wifi/service/java/com/android/server/wifi/WifiServiceImpl.java

    public synchronized boolean setWifiEnabled(String packageName, boolean enable)
            throws RemoteException {
        if (enforceChangePermission(packageName) != MODE_ALLOWED) {
            return false;
        }
       .........

        mWifiController.sendMessage(CMD_WIFI_TOGGLED);
        return true;
    }

6、WifiStateMachinePrime对CMD_WIFI_TOGGLED消息进行处理,切换到DeviceActiveState状态

/frameworks/opt/net/wifi/service/java/com/android/server/wifi/WifiStateMachinePrime.java

    class StaDisabledState extends State {
        @Override
        public boolean processMessage(Message msg) {
            switch (msg.what) {
                case CMD_WIFI_TOGGLED:
                    if (mSettingsStore.isWifiToggleEnabled()) {
                        if (doDeferEnable(msg)) {
                            if (mHaveDeferredEnable) {
                                //  have 2 toggles now, inc serial number and ignore both
                                mDeferredEnableSerialNumber++;
                            }
                            mHaveDeferredEnable = !mHaveDeferredEnable;
                            break;
                        }
                        transitionTo(mDeviceActiveState);

进入DeviceActiveState

    class DeviceActiveState extends State {
        @Override
        public void enter() {
            mWifiStateMachinePrime.enterClientMode();
            mWifiStateMachine.setHighPerfModeEnabled(false);
        }

执行enterClientMode函数,给ModeStateMachine状态机发送CMD_START_CLIENT_MODE消息

    public void enterClientMode() {
        changeMode(ModeStateMachine.CMD_START_CLIENT_MODE);
    }

下面我们看ModeStateMachine对CMD_START_CLIENT_MODE的处理

private class ModeStateMachine extends StateMachine {
   
    private boolean checkForAndHandleModeChange(Message message) {
        switch(message.what) {
            case ModeStateMachine.CMD_START_CLIENT_MODE:
                Log.d(TAG, "Switching from " + getCurrentMode() + " to ClientMode");
                mModeStateMachine.transitionTo(mClientModeActiveState);
                break;

然后我们看ClientModeActiveState的处理

class ClientModeActiveState extends ModeActiveState {
    @Override
    public void enter() {
        Log.d(TAG, "Entering ClientModeActiveState");
        mListener = new ClientListener();
        mManager = mWifiInjector.makeClientModeManager(mListener);
        mManager.start();
        mActiveModeManagers.add(mManager);
        updateBatteryStatsWifiState(true);
    }

7、ClientModeManager里首先是调用了start函数,如何发送消息CMD_START,消息是IdleState进行处理。
/frameworks/opt/net/wifi/service/java/com/android/server/wifi/ClientModeManager.java

    public void start() {
        mStateMachine.sendMessage(ClientModeStateMachine.CMD_START);
    }

我们看IdleState对CMD_START的处理方式:可以看到调用了wifinative的setupInterfaceForClientMode方法

        private class IdleState extends State {
            @Override
            public boolean processMessage(Message message) {
                switch (message.what) {
                    case CMD_START:
                        updateWifiState(WifiManager.WIFI_STATE_ENABLING,
                                        WifiManager.WIFI_STATE_DISABLED);

                        mClientInterfaceName = mWifiNative.setupInterfaceForClientMode(      //调用了wifinative的setupInterfaceForClientMode方法
                                false /* not low priority */, mWifiNativeInterfaceCallback);
                        if (TextUtils.isEmpty(mClientInterfaceName)) {
                            Log.e(TAG, "Failed to create ClientInterface. Sit in Idle");
                            updateWifiState(WifiManager.WIFI_STATE_UNKNOWN,
                                            WifiManager.WIFI_STATE_ENABLING);
                            updateWifiState(WifiManager.WIFI_STATE_DISABLED,
                                            WifiManager.WIFI_STATE_UNKNOWN);
                            break;
                return HANDLED;
            }
        }

8、下面我们看wifinative的setupInterfaceForClientMode方法

/frameworks/opt/net/wifi/service/java/com/android/server/wifi/WifiNative.java
我们看setupInterfaceForClientMode的相应处理,可以看到调用了startSupplicant函数

    public String setupInterfaceForClientMode(boolean lowPrioritySta,
            @NonNull InterfaceCallback interfaceCallback) {
            if (!startHal()) {
                Log.e(TAG, "Failed to start Hal");
                mWifiMetrics.incrementNumSetupClientInterfaceFailureDueToHal();
                return null;
            }
            if (!startSupplicant()) {
                Log.e(TAG, "Failed to start supplicant");
                mWifiMetrics.incrementNumSetupClientInterfaceFailureDueToSupplicant();
                return null;
            }
    }

启动supplicant

    private boolean startSupplicant() {
        synchronized (mLock) {
            if (!mIfaceMgr.hasAnyStaIface()) {
                if (!mWificondControl.enableSupplicant()) {
                    Log.e(TAG, "Failed to enable supplicant");
                    return false;
                }
    }

总结:Android9.0与8.0相比,Wifi主要是多了WifiStateMachinePrime(状态机的前处理机制),wifiService不在直接与WifiStateMachine交互,而是通过WifiStateMachinePrime进行处理,再送往WifiStateMachine,中间多了一层ClientModeManager,在这里面进行初始化wpa_supplicant工作。

关注公众号,获取更多开发必备知识
在这里插入图片描述

你可能感兴趣的:(WIfi,Android9.0,Wifi开启流程,Wifi使能,打开wifi)