WifiService由SystemServer创建,在WifiService的构造函数中会创建WifiServiceImpl实例:
//packages/modules/Wifi/service/java/com/android/server/wifi/WifiService.java
public final class WifiService extends SystemService {
private static final String TAG = "WifiService";
// Notification channels used by the wifi service.
public static final String NOTIFICATION_NETWORK_STATUS = "NETWORK_STATUS";
public static final String NOTIFICATION_NETWORK_ALERTS = "NETWORK_ALERTS";
public static final String NOTIFICATION_NETWORK_AVAILABLE = "NETWORK_AVAILABLE";
private final WifiServiceImpl mImpl;
private final WifiContext mWifiContext;
public WifiService(Context contextBase) {
super(contextBase);
mWifiContext = new WifiContext(contextBase); //创建WifiContext对象
WifiInjector injector = new WifiInjector(mWifiContext); //创建WifiInjector对象
mImpl = new WifiServiceImpl(mWifiContext, injector); //创建WifiServiceImpl对象
}
@Override
public void onStart() {
Log.i(TAG, "Registering " + Context.WIFI_SERVICE);
publishBinderService(Context.WIFI_SERVICE, mImpl);
}
@Override
public void onBootPhase(int phase) {
if (phase == SystemService.PHASE_SYSTEM_SERVICES_READY) {
mImpl.checkAndStartWifi();
} else if (phase == SystemService.PHASE_BOOT_COMPLETED) {
mImpl.handleBootCompleted();
}
}
@Override
public void onUserSwitching(TargetUser from, TargetUser to) {
mImpl.handleUserSwitch(to.getUserHandle().getIdentifier());
}
@Override
public void onUserUnlocking(TargetUser user) {
mImpl.handleUserUnlock(user.getUserHandle().getIdentifier());
}
@Override
public void onUserStopping(TargetUser user) {
mImpl.handleUserStop(user.getUserHandle().getIdentifier());
}
}
在WifiServiceImpl的构造函数中会通过WifiInjector获取Wifi相关实例:
//packages/modules/Wifi/service/java/com/android/server/wifi/WifiServiceImpl.java
public class WifiServiceImpl extends BaseWifiService {
public WifiServiceImpl(WifiContext context, WifiInjector wifiInjector) {
mContext = context;
mWifiInjector = wifiInjector;
mClock = wifiInjector.getClock();
mFacade = mWifiInjector.getFrameworkFacade();
mWifiMetrics = mWifiInjector.getWifiMetrics();
mWifiTrafficPoller = mWifiInjector.getWifiTrafficPoller();
mUserManager = mWifiInjector.getUserManager();
mCountryCode = mWifiInjector.getWifiCountryCode();
mActiveModeWarden = mWifiInjector.getActiveModeWarden();
mScanRequestProxy = mWifiInjector.getScanRequestProxy();
mSettingsStore = mWifiInjector.getWifiSettingsStore();
mPowerManager = mContext.getSystemService(PowerManager.class);
mAppOps = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
mWifiLockManager = mWifiInjector.getWifiLockManager();
mWifiMulticastLockManager = mWifiInjector.getWifiMulticastLockManager();
mWifiBackupRestore = mWifiInjector.getWifiBackupRestore();
mSoftApBackupRestore = mWifiInjector.getSoftApBackupRestore();
mWifiApConfigStore = mWifiInjector.getWifiApConfigStore();
mWifiPermissionsUtil = mWifiInjector.getWifiPermissionsUtil();
mLog = mWifiInjector.makeLog(TAG);
mFrameworkFacade = wifiInjector.getFrameworkFacade();
mTetheredSoftApTracker = new TetheredSoftApTracker();
mActiveModeWarden.registerSoftApCallback(mTetheredSoftApTracker);
mLohsSoftApTracker = new LohsSoftApTracker();
mActiveModeWarden.registerLohsCallback(mLohsSoftApTracker);
mWifiNetworkSuggestionsManager = mWifiInjector.getWifiNetworkSuggestionsManager();
mDppManager = mWifiInjector.getDppManager();
mWifiThreadRunner = mWifiInjector.getWifiThreadRunner();
mWifiHandlerThread = mWifiInjector.getWifiHandlerThread();
mWifiConfigManager = mWifiInjector.getWifiConfigManager();
mHalDeviceManager = mWifiInjector.getHalDeviceManager();
mWifiBlocklistMonitor = mWifiInjector.getWifiBlocklistMonitor();
mPasspointManager = mWifiInjector.getPasspointManager();
mWifiScoreCard = mWifiInjector.getWifiScoreCard();
mWifiHealthMonitor = wifiInjector.getWifiHealthMonitor();
mMemoryStoreImpl = new MemoryStoreImpl(mContext, mWifiInjector,
mWifiScoreCard, mWifiHealthMonitor);
mWifiConnectivityManager = wifiInjector.getWifiConnectivityManager();
mWifiDataStall = wifiInjector.getWifiDataStall();
mWifiNative = wifiInjector.getWifiNative();
mCoexManager = wifiInjector.getCoexManager();
mConnectHelper = wifiInjector.getConnectHelper();
mWifiGlobals = wifiInjector.getWifiGlobals();
mSimRequiredNotifier = wifiInjector.getSimRequiredNotifier();
mWifiCarrierInfoManager = wifiInjector.getWifiCarrierInfoManager();
mMakeBeforeBreakManager = mWifiInjector.getMakeBeforeBreakManager();
mLastCallerInfoManager = mWifiInjector.getLastCallerInfoManager();
mWifiDialogManager = mWifiInjector.getWifiDialogManager();
mBuildProperties = mWifiInjector.getBuildProperties();
mDefaultClientModeManager = mWifiInjector.getDefaultClientModeManager();
mCountryCodeTracker = new CountryCodeTracker();
mWifiTetheringDisallowed = false;
mMultiInternetManager = mWifiInjector.getMultiInternetManager();
}
}
checkAndStartWifi流程
在系统启动过程中,SystemService会调用WifiService的onBootPhase回调,通知系统启动阶段,在接收到phase 为PHASE_SYSTEM_SERVICES_READY时调用WifiServiceImpl的checkAndStartWifi方法:
WifiServiceImpl的checkAndStartWifi方法:
//packages/modules/Wifi/service/java/com/android/server/wifi/WifiService.java
public class WifiServiceImpl extends BaseWifiService {
private final ActiveModeWarden mActiveModeWarden;
private final WifiConfigManager mWifiConfigManager;
private final WifiThreadRunner mWifiThreadRunner;
private final WifiSettingsStore mSettingsStore;
private final WifiGlobals mWifiGlobals;
private final WifiInjector mWifiInjector;
public void checkAndStartWifi() {
mWifiThreadRunner.post(() -> {
if (!mWifiConfigManager.loadFromStore()) {
Log.e(TAG, "Failed to load from config store");
}
if (!mWifiGlobals.isInsecureEnterpriseConfigurationAllowed()) {
mWifiConfigManager.updateTrustOnFirstUseFlag(isTrustOnFirstUseSupported());
}
mWifiConfigManager.incrementNumRebootsSinceLastUse();
// config store is read, check if verbose logging is enabled.
enableVerboseLoggingInternal(
mWifiInjector.getSettingsConfigStore().get(WIFI_VERBOSE_LOGGING_ENABLED)
? 1 : 0);
// Check if wi-fi needs to be enabled
boolean wifiEnabled = mSettingsStore.isWifiToggleEnabled();
Log.i(TAG,
"WifiService starting up with Wi-Fi " + (wifiEnabled ? "enabled" : "disabled"));
mWifiInjector.getWifiScanAlwaysAvailableSettingsCompatibility().initialize();
mWifiInjector.getWifiNotificationManager().createNotificationChannels();
//注册ACTION_SIM_CARD_STATE_CHANGED广播
mContext.registerReceiver(
new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int state = intent.getIntExtra(TelephonyManager.EXTRA_SIM_STATE,
TelephonyManager.SIM_STATE_UNKNOWN);
if (TelephonyManager.SIM_STATE_ABSENT == state) {
Log.d(TAG, "resetting networks because SIM was removed");
resetCarrierNetworks(RESET_SIM_REASON_SIM_REMOVED);
}
}
},
new IntentFilter(TelephonyManager.ACTION_SIM_CARD_STATE_CHANGED),
null,
new Handler(mWifiHandlerThread.getLooper()));
//注册RESET_SIM_REASON_SIM_INSERTED广播
mContext.registerReceiver(
new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int state = intent.getIntExtra(TelephonyManager.EXTRA_SIM_STATE,
TelephonyManager.SIM_STATE_UNKNOWN);
if (TelephonyManager.SIM_STATE_LOADED == state) {
Log.d(TAG, "resetting networks because SIM was loaded");
resetCarrierNetworks(RESET_SIM_REASON_SIM_INSERTED);
}
}
},
new IntentFilter(TelephonyManager.ACTION_SIM_APPLICATION_STATE_CHANGED),
null,
new Handler(mWifiHandlerThread.getLooper()));
//注册ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED广播
mContext.registerReceiver(
new BroadcastReceiver() {
private int mLastSubId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
@Override
public void onReceive(Context context, Intent intent) {
final int subId = intent.getIntExtra("subscription",
SubscriptionManager.INVALID_SUBSCRIPTION_ID);
if (subId != mLastSubId) {
Log.d(TAG, "resetting networks as default data SIM is changed");
resetCarrierNetworks(RESET_SIM_REASON_DEFAULT_DATA_SIM_CHANGED);
mLastSubId = subId;
mWifiDataStall.resetPhoneStateListener();
}
}
},
new IntentFilter(TelephonyManager.ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED),
null,
new Handler(mWifiHandlerThread.getLooper()));
//注册ACTION_NETWORK_COUNTRY_CHANGED广播
mContext.registerReceiver(
new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String countryCode = intent.getStringExtra(
TelephonyManager.EXTRA_NETWORK_COUNTRY);
Log.d(TAG, "Country code changed to :" + countryCode);
mCountryCode.setTelephonyCountryCodeAndUpdate(countryCode);
}
},
new IntentFilter(TelephonyManager.ACTION_NETWORK_COUNTRY_CHANGED),
null,
new Handler(mWifiHandlerThread.getLooper()));
//注册ACTION_LOCALE_CHANGED广播
mContext.registerReceiver(
new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "locale changed");
resetNotificationManager();
}
},
new IntentFilter(Intent.ACTION_LOCALE_CHANGED),
null,
new Handler(mWifiHandlerThread.getLooper()));
//注册MODE_CHANGED_ACTION广播
mContext.registerReceiver(
new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (isVerboseLoggingEnabled()) {
Log.v(TAG, "onReceive: MODE_CHANGED_ACTION: intent=" + intent);
}
updateLocationMode();
}
},
new IntentFilter(LocationManager.MODE_CHANGED_ACTION),
null,
new Handler(mWifiHandlerThread.getLooper()));
updateLocationMode(); //更新本地模式
if (SdkLevel.isAtLeastT()) {
//注册ACTION_USER_RESTRICTIONS_CHANGED广播
mContext.registerReceiver(
new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "user restrictions changed");
onUserRestrictionsChanged();
}
},
new IntentFilter(UserManager.ACTION_USER_RESTRICTIONS_CHANGED),
null,
new Handler(mWifiHandlerThread.getLooper()));
mWifiTetheringDisallowed = mUserManager.getUserRestrictions()
.getBoolean(UserManager.DISALLOW_WIFI_TETHERING);
}
// Adding optimizations of only receiving broadcasts when wifi is enabled
// can result in race conditions when apps toggle wifi in the background
// without active user involvement. Always receive broadcasts.
registerForBroadcasts(); //注册package相关广播
mInIdleMode = mPowerManager.isDeviceIdleMode();
mActiveModeWarden.start(); //调用ActiveModeWarden的start方法
registerForCarrierConfigChange(); //注册运营商配置更改
mWifiInjector.getAdaptiveConnectivityEnabledSettingObserver().initialize();
mIsWifiServiceStarted = true;
});
}
private void updateLocationMode() {
mIsLocationModeEnabled = mWifiPermissionsUtil.isLocationModeEnabled();
mWifiConnectivityManager.setLocationModeEnabled(mIsLocationModeEnabled);
}
private void registerForBroadcasts() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_PACKAGE_FULLY_REMOVED);
intentFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
intentFilter.addDataScheme("package");
mContext.registerReceiver(
new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
Uri uri = intent.getData();
if (uid == -1 || uri == null) {
Log.e(TAG, "Uid or Uri is missing for action:" + intent.getAction());
return;
}
String pkgName = uri.getSchemeSpecificPart();
PackageManager pm = context.getPackageManager();
PackageInfo packageInfo = null;
try {
packageInfo = pm.getPackageInfo(pkgName, 0);
} catch (PackageManager.NameNotFoundException e) {
Log.w(TAG, "Couldn't get PackageInfo for package:" + pkgName);
}
// If package is not removed or disabled, just ignore.
if (packageInfo != null
&& packageInfo.applicationInfo != null
&& packageInfo.applicationInfo.enabled) {
return;
}
Log.d(TAG, "Remove settings for package:" + pkgName);
removeAppStateInternal(uid, pkgName);
}
},
intentFilter,
null,
new Handler(mWifiHandlerThread.getLooper()));
}
private void registerForCarrierConfigChange() {
IntentFilter filter = new IntentFilter();
filter.addAction(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
mContext.registerReceiver(
new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final int subId = SubscriptionManager.getActiveDataSubscriptionId();
Log.d(TAG, "ACTION_CARRIER_CONFIG_CHANGED, active subId: " + subId);
// Tether mode only since carrier requirement only for tethered SoftAp.
mTetheredSoftApTracker
.updateSoftApCapabilityWhenCarrierConfigChanged(subId);
mActiveModeWarden.updateSoftApCapability(
mTetheredSoftApTracker.getSoftApCapability(),
WifiManager.IFACE_IP_MODE_TETHERED);
}
},
filter,
null,
new Handler(mWifiHandlerThread.getLooper()));
WifiPhoneStateListener phoneStateListener = new WifiPhoneStateListener(
mWifiHandlerThread.getLooper());
mContext.getSystemService(TelephonyManager.class).listen(
phoneStateListener, PhoneStateListener.LISTEN_ACTIVE_DATA_SUBSCRIPTION_ID_CHANGE);
}
}
调用ActiveModeWarden的start方法:
//packages/modules/Wifi/service/java/com/android/server/wifi/util/ActiveModeWarden.java
public class ActiveModeWarden {
private final WifiController mWifiController;
public void start() {
//监听MODE_CHANGED_ACTION广播
mContext.registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Location mode has been toggled... trigger with the scan change
// update to make sure we are in the correct mode
scanAlwaysModeChanged();
}
}, new IntentFilter(LocationManager.MODE_CHANGED_ACTION));
//监听ACTION_AIRPLANE_MODE_CHANGED广播
mContext.registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
boolean airplaneModeUpdated = mSettingsStore.updateAirplaneModeTracker();
boolean userRestrictionSet =
SdkLevel.isAtLeastT() && mUserManager.hasUserRestrictionForUser(
UserManager.DISALLOW_CHANGE_WIFI_STATE,
UserHandle.getUserHandleForUid(Process.SYSTEM_UID));
if (!userRestrictionSet && airplaneModeUpdated) {
mSettingsStore.handleAirplaneModeToggled();
airplaneModeToggled();
}
}
}, new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
//监听ACTION_EMERGENCY_CALLBACK_MODE_CHANGED广播
mContext.registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
boolean emergencyMode =
intent.getBooleanExtra(TelephonyManager.EXTRA_PHONE_IN_ECM_STATE, false);
emergencyCallbackModeChanged(emergencyMode);
}
}, new IntentFilter(TelephonyManager.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED));
boolean trackEmergencyCallState = mContext.getResources().getBoolean(
R.bool.config_wifi_turn_off_during_emergency_call);
if (trackEmergencyCallState) {
//监听ACTION_EMERGENCY_CALL_STATE_CHANGED广播
mContext.registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
boolean inCall = intent.getBooleanExtra(
TelephonyManager.EXTRA_PHONE_IN_EMERGENCY_CALL, false);
emergencyCallStateChanged(inCall);
}
}, new IntentFilter(TelephonyManager.ACTION_EMERGENCY_CALL_STATE_CHANGED));
}
mWifiController.start(); //调用WifiController的start方法
}
}
调用ActiveModeWarden内部类WifiController的start方法:
//packages/modules/Wifi/service/java/com/android/server/wifi/util/ActiveModeWarden.java
public class ActiveModeWarden {
private final WifiNative mWifiNative;
private class WifiController extends StateMachine {
public void start() {
boolean isAirplaneModeOn = mSettingsStore.isAirplaneModeOn();
boolean isWifiEnabled = mSettingsStore.isWifiToggleEnabled();
boolean isScanningAlwaysAvailable = mSettingsStore.isScanAlwaysAvailable();
boolean isLocationModeActive = mWifiPermissionsUtil.isLocationModeEnabled();
log("isAirplaneModeOn = " + isAirplaneModeOn
+ ", isWifiEnabled = " + isWifiEnabled
+ ", isScanningAvailable = " + isScanningAlwaysAvailable
+ ", isLocationModeActive = " + isLocationModeActive);
// Initialize these values at bootup to defaults, will be overridden by API calls
// for further toggles.
mLastPrimaryClientModeManagerRequestorWs = mFacade.getSettingsWorkSource(mContext);
mLastScanOnlyClientModeManagerRequestorWs = INTERNAL_REQUESTOR_WS;
ActiveModeManager.ClientRole role = getRoleForPrimaryOrScanOnlyClientModeManager();
if (role == ROLE_CLIENT_PRIMARY) {
startPrimaryClientModeManager(mLastPrimaryClientModeManagerRequestorWs);
setInitialState(mEnabledState);
} else if (role == ROLE_CLIENT_SCAN_ONLY) {
startScanOnlyClientModeManager(mLastScanOnlyClientModeManagerRequestorWs);
setInitialState(mEnabledState);
} else {
setInitialState(mDisabledState);
}
mWifiMetrics.noteWifiEnabledDuringBoot(mSettingsStore.isWifiToggleEnabled());
// Initialize the lower layers before we start.
mWifiNative.initialize(); //初始化WifiNative
super.start(); //调用父类的start方法,启动状态机
}
}
handleBootCompleted流程
在系统启动过程中,SystemService会调用WifiService的onBootPhase回调,通知系统启动阶段,在接收到phase为PHASE_BOOT_COMPLETED时调用WifiServiceImpl的handleBootCompleted方法:
WifiServiceImpl的handleBootCompleted方法:
//packages/modules/Wifi/service/java/com/android/server/wifi/WifiService.java
public class WifiServiceImpl extends BaseWifiService {
private final MemoryStoreImpl mMemoryStoreImpl;
private final PasspointManager mPasspointManager;
private final TetheredSoftApTracker mTetheredSoftApTracker;
private final LohsSoftApTracker mLohsSoftApTracker;
public void handleBootCompleted() {
mWifiThreadRunner.post(() -> {
Log.d(TAG, "Handle boot completed");
// Register for system broadcasts.
//注册系统广播。
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_USER_REMOVED);
intentFilter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
intentFilter.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
intentFilter.addAction(Intent.ACTION_SHUTDOWN);
mContext.registerReceiver(
new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_USER_REMOVED.equals(action)) {
UserHandle userHandle =
intent.getParcelableExtra(Intent.EXTRA_USER);
if (userHandle == null) {
Log.e(TAG,
"User removed broadcast received with no user handle");
return;
}
mWifiConfigManager
.removeNetworksForUser(userHandle.getIdentifier());
} else if (BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED
.equals(action)) {
int state = intent.getIntExtra(
BluetoothAdapter.EXTRA_CONNECTION_STATE,
BluetoothAdapter.STATE_DISCONNECTED);
boolean isConnected =
state != BluetoothAdapter.STATE_DISCONNECTED;
mWifiGlobals.setBluetoothConnected(isConnected);
for (ClientModeManager cmm :
mActiveModeWarden.getClientModeManagers()) {
cmm.onBluetoothConnectionStateChanged();
}
} else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
BluetoothAdapter.STATE_OFF);
boolean isEnabled = state != BluetoothAdapter.STATE_OFF;
mWifiGlobals.setBluetoothEnabled(isEnabled);
for (ClientModeManager cmm :
mActiveModeWarden.getClientModeManagers()) {
cmm.onBluetoothConnectionStateChanged();
}
} else if (PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED
.equals(action)) {
handleIdleModeChanged();
} else if (Intent.ACTION_SHUTDOWN.equals(action)) {
handleShutDown();
}
}
},
intentFilter,
null,
new Handler(mWifiHandlerThread.getLooper()));
mMemoryStoreImpl.start();
mPasspointManager.initializeProvisioner(
mWifiInjector.getPasspointProvisionerHandlerThread().getLooper());
mWifiInjector.getWifiNetworkFactory().register(); //调用WifiNetworkFactory的register方法
mWifiInjector.getUntrustedWifiNetworkFactory().register(); //调用UntrustedWifiNetworkFactory的register方法
mWifiInjector.getRestrictedWifiNetworkFactory().register(); //调用RestrictedWifiNetworkFactory的register方法
mWifiInjector.getOemWifiNetworkFactory().register(); //调用OemWifiNetworkFactory的register方法
mWifiInjector.getMultiInternetWifiNetworkFactory().register(); //调用MultiInternetWifiNetworkFactory的register方法
mWifiInjector.getWifiP2pConnection().handleBootCompleted();
// Start to listen country code change to avoid query supported channels causes boot
// time increased.
mCountryCode.registerListener(mCountryCodeTracker);
mTetheredSoftApTracker.handleBootCompleted();
mLohsSoftApTracker.handleBootCompleted();
mWifiInjector.getSarManager().handleBootCompleted();
mIsBootComplete = true;
});
}
}