当前位置:   article > 正文

Android R WiFi热点流程浅析_android热点 路由规则

android热点 路由规则

 Android R WiFi热点流程浅析

    Android上的WiFi SoftAp功能是用户常用的功能之一,它能让我们分享手机的网络给其他设备使用。

   那Android系统是如何实现SoftAp的呢,这里在FWK层面做一个简要的流程分析,供自己记录和大家参考。

   以Android R版本为例,我们知道Android大部分的系统FWK服务都在SystemServer中启动,SoftAp的Service也不例外:

  1. /**
  2. * Use with {@link #getSystemService(String)} to retrieve a {@link android.net.TetheringManager}
  3. * for managing tethering functions.
  4. * @hide
  5. * @see android.net.TetheringManager
  6. */
  7. @SystemApi
  8. public static final String TETHERING_SERVICE = "tethering";
  9. private static final String TETHERING_CONNECTOR_CLASS = "android.net.ITetheringConnector";
  10. /**
  11. * Starts a miscellaneous grab bag of stuff that has yet to be refactored and organized.
  12. */
  13. private void startOtherServices(@NonNull TimingsTraceAndSlog t) {
  14. t.traceBegin("startOtherServices");
  15. ......
  16. t.traceBegin("StartTethering");
  17. try {
  18. // TODO: hide implementation details, b/146312721.
  19. ConnectivityModuleConnector.getInstance().startModuleService(
  20. TETHERING_CONNECTOR_CLASS,
  21. PERMISSION_MAINLINE_NETWORK_STACK, service -> {
  22. ServiceManager.addService(Context.TETHERING_SERVICE, service,
  23. false /* allowIsolated */,
  24. DUMP_FLAG_PRIORITY_HIGH | DUMP_FLAG_PRIORITY_NORMAL);
  25. });
  26. } catch (Throwable e) {
  27. reportWtf("starting Tethering", e);
  28. }
  29. t.traceEnd();
  30. ......
  31. }

这里借助了ConnectivityModuleConnector工具类的startModuleService()函数去启动、绑定服务:

  1. /**
  2. * Start a module running in the network stack or system_server process. Should be called only
  3. * once for each module per device startup.
  4. *
  5. * <p>This method will start a networking module either in the network stack
  6. * process, or inside the system server on devices that do not support the corresponding
  7. * mainline network . The corresponding networking module service's binder
  8. * object will then be delivered asynchronously via the provided {@link ModuleServiceCallback}.
  9. *
  10. * @param serviceIntentBaseAction Base action to use for constructing the intent needed to
  11. * bind to the corresponding module.
  12. * @param servicePermissionName Permission to be held by the corresponding module.
  13. */
  14. public void startModuleService(
  15. @NonNull String serviceIntentBaseAction,
  16. @NonNull String servicePermissionName,
  17. @NonNull ModuleServiceCallback callback) {
  18. log("Starting networking module " + serviceIntentBaseAction);
  19. final PackageManager pm = mContext.getPackageManager();
  20. // Try to bind in-process if the device was shipped with an in-process version
  21. Intent intent = mDeps.getModuleServiceIntent(pm, serviceIntentBaseAction,
  22. servicePermissionName, true /* inSystemProcess */);
  23. // Otherwise use the updatable module version
  24. if (intent == null) {
  25. intent = mDeps.getModuleServiceIntent(pm, serviceIntentBaseAction,
  26. servicePermissionName, false /* inSystemProcess */);
  27. log("Starting networking module in network_stack process");
  28. } else {
  29. log("Starting networking module in system_server process");
  30. }
  31. if (intent == null) {
  32. maybeCrashWithTerribleFailure("Could not resolve the networking module", null);
  33. return;
  34. }
  35. final String packageName = intent.getComponent().getPackageName();
  36. // Start the network stack. The service will be added to the service manager by the
  37. // corresponding client in ModuleServiceCallback.onModuleServiceConnected().
  38. if (!mContext.bindServiceAsUser(
  39. intent, new ModuleServiceConnection(packageName, callback),
  40. Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT, UserHandle.SYSTEM)) {
  41. maybeCrashWithTerribleFailure(
  42. "Could not bind to networking module in-process, or in app with "
  43. + intent, packageName);
  44. return;
  45. }
  46. log("Networking module service start requested");
  47. }
  48. private class ModuleServiceConnection implements ServiceConnection {
  49. @NonNull
  50. private final String mPackageName;
  51. @NonNull
  52. private final ModuleServiceCallback mModuleServiceCallback;
  53. private ModuleServiceConnection(
  54. @NonNull String packageName,
  55. @NonNull ModuleServiceCallback moduleCallback) {
  56. mPackageName = packageName;
  57. mModuleServiceCallback = moduleCallback;
  58. }
  59. @Override
  60. public void onServiceConnected(ComponentName name, IBinder service) {
  61. logi("Networking module service connected");
  62. mModuleServiceCallback.onModuleServiceConnected(service);
  63. }
  64. @Override
  65. public void onServiceDisconnected(ComponentName name) {
  66. // onServiceDisconnected is not being called on device shutdown, so this method being
  67. // called always indicates a bad state for the system server.
  68. // This code path is only run by the system server: only the system server binds
  69. // to the NetworkStack as a service. Other processes get the NetworkStack from
  70. // the ServiceManager.
  71. maybeCrashWithTerribleFailure("Lost network stack", mPackageName);
  72. }
  73. }

结合代码可知,就是通过bindService()启动一个服务,并通过一个lambda表达式在服务connect成功之后进行服务注册的过程,它绑定的服务的filter是:android.net.ITetheringConnector。

在源码中,该服务定义在frameworks\base\packages\Tethering\AndroidManifest.xml中:

  1. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  2. package="com.android.networkstack.tethering"
  3. android:sharedUserId="android.uid.networkstack">
  4. <uses-sdk android:minSdkVersion="29" android:targetSdkVersion="29" />
  5. <!-- Permissions must be defined here, and not in the base manifest, as the tethering
  6. running in the system server process does not need any permission, and having
  7. privileged permissions added would cause crashes on startup unless they are also
  8. added to the privileged permissions whitelist for that package. -->
  9. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  10. <uses-permission android:name="android.permission.BLUETOOTH" />
  11. <uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED" />
  12. <uses-permission android:name="android.permission.BROADCAST_STICKY" />
  13. <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
  14. <uses-permission android:name="android.permission.MANAGE_USB" />
  15. <uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />
  16. <uses-permission android:name="android.permission.READ_DEVICE_CONFIG" />
  17. <uses-permission android:name="android.permission.READ_NETWORK_USAGE_HISTORY" />
  18. <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
  19. <uses-permission android:name="android.permission.TETHER_PRIVILEGED" />
  20. <uses-permission android:name="android.permission.UPDATE_APP_OPS_STATS" />
  21. <uses-permission android:name="android.permission.UPDATE_DEVICE_STATS" />
  22. <uses-permission android:name="android.permission.WRITE_SETTINGS" />
  23. <protected-broadcast android:name="com.android.server.connectivity.tethering.DISABLE_TETHERING" />
  24. <application
  25. android:process="com.android.networkstack.process"
  26. android:extractNativeLibs="false"
  27. android:persistent="true">
  28. <service android:name="com.android.networkstack.tethering.TetheringService"
  29. android:permission="android.permission.MAINLINE_NETWORK_STACK"
  30. android:exported="true">
  31. <intent-filter>
  32. <action android:name="android.net.ITetheringConnector"/>
  33. </intent-filter>
  34. </service>
  35. </application>
  36. </manifest>

它对应的Service是TetheringService,Tethering.apk封装了网络共享相关的主要服务实现,它的使用类似于Bluetooth.apk,被bind service拉起随后运行;继续看TetheringService:

  1. /*
  2. * Copyright (C) 2019 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.android.networkstack.tethering;
  17. /**
  18. * Android service used to manage tethering.
  19. *
  20. * <p>The service returns a binder for the system server to communicate with the tethering.
  21. */
  22. public class TetheringService extends Service {
  23. private static final String TAG = TetheringService.class.getSimpleName();
  24. private TetheringConnector mConnector;
  25. @Override
  26. public void onCreate() {
  27. final TetheringDependencies deps = makeTetheringDependencies();
  28. // The Tethering object needs a fully functional context to start, so this can't be done
  29. // in the constructor.
  30. mConnector = new TetheringConnector(makeTethering(deps), TetheringService.this);
  31. }
  32. /**
  33. * Make a reference to Tethering object.
  34. */
  35. @VisibleForTesting
  36. public Tethering makeTethering(TetheringDependencies deps) {
  37. System.loadLibrary("tetherutilsjni");
  38. return new Tethering(deps);
  39. }
  40. @NonNull
  41. @Override
  42. public IBinder onBind(Intent intent) {
  43. return mConnector;
  44. }
  45. private static class TetheringConnector extends ITetheringConnector.Stub {
  46. private final TetheringService mService;
  47. private final Tethering mTethering;
  48. TetheringConnector(Tethering tether, TetheringService service) {
  49. mTethering = tether;
  50. mService = service;
  51. }
  52. }
  53. }
  54. /** @hide */
  55. oneway interface ITetheringConnector {
  56. void tether(String iface, String callerPkg, IIntResultListener receiver);
  57. void untether(String iface, String callerPkg, IIntResultListener receiver);
  58. void setUsbTethering(boolean enable, String callerPkg, IIntResultListener receiver);
  59. void startTethering(in TetheringRequestParcel request, String callerPkg,
  60. IIntResultListener receiver);
  61. void stopTethering(int type, String callerPkg, IIntResultListener receiver);
  62. void requestLatestTetheringEntitlementResult(int type, in ResultReceiver receiver,
  63. boolean showEntitlementUi, String callerPkg);
  64. void registerTetheringEventCallback(ITetheringEventCallback callback, String callerPkg);
  65. void unregisterTetheringEventCallback(ITetheringEventCallback callback, String callerPkg);
  66. void isTetheringSupported(String callerPkg, IIntResultListener receiver);
  67. void stopAllTethering(String callerPkg, IIntResultListener receiver);
  68. }

TetheringService主要实现了AIDL ITetheringConnector定义的业务接口,根据function名称可以很清晰的知道,它主要针对的是网络共享。服务启动成功,会以tethering的名字注册进系统中,其他需要使用的组件就可以很容易的向Android查询、获取它。

Tethering组件正常启动之后,就是APP使用它了;我们以CarSetting为例:

  1. /**
  2. * Fragment to host tethering-related preferences.
  3. */
  4. @SearchIndexable
  5. public class WifiTetherFragment extends SettingsFragment {
  6. private TetheringManager mTetheringManager;
  7. private void startTethering() {
  8. mTetheringManager.startTethering(ConnectivityManager.TETHERING_WIFI,
  9. ConcurrentUtils.DIRECT_EXECUTOR,
  10. new TetheringManager.StartTetheringCallback() {
  11. @Override
  12. public void onTetheringFailed(final int result) {
  13. mTetherSwitch.setChecked(false);
  14. mTetherSwitch.setEnabled(true);
  15. }
  16. });
  17. }
  18. private void stopTethering() {
  19. mTetheringManager.stopTethering(ConnectivityManager.TETHERING_WIFI);
  20. }
  21. private void restartTethering() {
  22. stopTethering();
  23. mRestartBooked = true;
  24. }
  25. }

WifiTetherFragment是实现开关热点的Fragment,可知它会调用TetherManager::startTethering()去开启WiFi共享,TetheringManager内部通过ITetheringConnector实现具体功能,类似于WifiManager:

  1. /**
  2. * Starts tethering and runs tether provisioning for the given type if needed. If provisioning
  3. * fails, stopTethering will be called automatically.
  4. *
  5. * <p>Without {@link android.Manifest.permission.TETHER_PRIVILEGED} permission, the call will
  6. * fail if a tethering entitlement check is required.
  7. *
  8. * @param request a {@link TetheringRequest} which can specify the preferred configuration.
  9. * @param executor {@link Executor} to specify the thread upon which the callback of
  10. * TetheringRequest will be invoked.
  11. * @param callback A callback that will be called to indicate the success status of the
  12. * tethering start request.
  13. */
  14. @RequiresPermission(anyOf = {
  15. android.Manifest.permission.TETHER_PRIVILEGED,
  16. android.Manifest.permission.WRITE_SETTINGS
  17. })
  18. public void startTethering(@NonNull final TetheringRequest request,
  19. @NonNull final Executor executor, @NonNull final StartTetheringCallback callback) {
  20. final String callerPkg = mContext.getOpPackageName();
  21. Log.i(TAG, "startTethering caller:" + callerPkg);
  22. final IIntResultListener listener = new IIntResultListener.Stub() {
  23. @Override
  24. public void onResult(final int resultCode) {
  25. executor.execute(() -> {
  26. if (resultCode == TETHER_ERROR_NO_ERROR) {
  27. callback.onTetheringStarted();
  28. } else {
  29. callback.onTetheringFailed(resultCode);
  30. }
  31. });
  32. }
  33. };
  34. getConnector(c -> c.startTethering(request.getParcel(), callerPkg, listener));
  35. }
  36. /**
  37. * Starts tethering and runs tether provisioning for the given type if needed. If provisioning
  38. * fails, stopTethering will be called automatically.
  39. *
  40. * <p>Without {@link android.Manifest.permission.TETHER_PRIVILEGED} permission, the call will
  41. * fail if a tethering entitlement check is required.
  42. *
  43. * @param type The tethering type, on of the {@code TetheringManager#TETHERING_*} constants.
  44. * @param executor {@link Executor} to specify the thread upon which the callback of
  45. * TetheringRequest will be invoked.
  46. * @hide
  47. */
  48. @RequiresPermission(anyOf = {
  49. android.Manifest.permission.TETHER_PRIVILEGED,
  50. android.Manifest.permission.WRITE_SETTINGS
  51. })
  52. @SystemApi(client = MODULE_LIBRARIES)
  53. public void startTethering(int type, @NonNull final Executor executor,
  54. @NonNull final StartTetheringCallback callback) {
  55. startTethering(new TetheringRequest.Builder(type).build(), executor, callback);
  56. }

从前述可知,传入的Tethering type是ConnectivityManager.TETHERING_WIFI,直接看TetheringService:

  1. private final Tethering mTethering;
  2. @Override
  3. public void startTethering(TetheringRequestParcel request, String callerPkg,
  4. IIntResultListener listener) {
  5. if (checkAndNotifyCommonError(callerPkg,
  6. request.exemptFromEntitlementCheck /* onlyAllowPrivileged */,
  7. listener)) {
  8. return;
  9. }
  10. m

Tethering是一个包含各种网络共享业务逻辑的实现类,比如BT网络共享、USB网络共享,以及我们这里关注的WiFi网络共享:

  1. /**
  2. *
  3. * This class holds much of the business logic to allow Android devices
  4. * to act as IP gateways via USB, BT, and WiFi interfaces.
  5. */
  6. public class Tethering {
  7. public Tethering(TetheringDependencies deps) {
  8. ......
  9. startStateMachineUpdaters();
  10. }
  11. /**
  12. * Start to register callbacks.
  13. * Call this function when tethering is ready to handle callback events.
  14. */
  15. private void startStateMachineUpdaters() {
  16. try {
  17. mNetd.registerUnsolicitedEventListener(mNetdCallback);
  18. } catch (RemoteException e) {
  19. mLog.e("Unable to register netd UnsolicitedEventListener");
  20. }
  21. mCarrierConfigChange.startListening();
  22. mContext.getSystemService(TelephonyManager.class).listen(mActiveDataSubIdListener,
  23. PhoneStateListener.LISTEN_ACTIVE_DATA_SUBSCRIPTION_ID_CHANGE);
  24. IntentFilter filter = new IntentFilter();
  25. filter.addAction(UsbManager.ACTION_USB_STATE);
  26. filter.addAction(CONNECTIVITY_ACTION);
  27. filter.addAction(WifiManager.WIFI_AP_STATE_CHANGED_ACTION);
  28. filter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
  29. filter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
  30. filter.addAction(UserManager.ACTION_USER_RESTRICTIONS_CHANGED);
  31. filter.addAction(ACTION_RESTRICT_BACKGROUND_CHANGED);
  32. mContext.registerReceiver(mStateReceiver, filter, null, mHandler);
  33. final IntentFilter noUpstreamFilter = new IntentFilter();
  34. noUpstreamFilter.addAction(TetheringNotificationUpdater.ACTION_DISABLE_TETHERING);
  35. mContext.registerReceiver(
  36. mStateReceiver, noUpstreamFilter, PERMISSION_MAINLINE_NETWORK_STACK, mHandler);
  37. final WifiManager wifiManager = getWifiManager();
  38. if (wifiManager != null) {
  39. wifiManager.registerSoftApCallback(mExecutor, new TetheringSoftApCallback());
  40. }
  41. startTrackDefaultNetwork();
  42. }
  43. private class StateReceiver extends BroadcastReceiver {
  44. @Override
  45. public void onReceive(Context content, Intent intent) {
  46. final String action = intent.getAction();
  47. if (action == null) return;
  48. if (action.equals(UsbManager.ACTION_USB_STATE)) {
  49. handleUsbAction(intent);
  50. } else if (action.equals(CONNECTIVITY_ACTION)) {
  51. handleConnectivityAction(intent);
  52. } else if (action.equals(WifiManager.WIFI_AP_STATE_CHANGED_ACTION)) {
  53. handleWifiApAction(intent);
  54. } else if (action.equals(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION)) {
  55. handleWifiP2pAction(intent);
  56. } else if (action.equals(Intent.ACTION_CONFIGURATION_CHANGED)) {
  57. mLog.log("OBSERVED configuration changed");
  58. updateConfiguration();
  59. } else if (action.equals(UserManager.ACTION_USER_RESTRICTIONS_CHANGED)) {
  60. mLog.log("OBSERVED user restrictions changed");
  61. handleUserRestrictionAction();
  62. } else if (action.equals(ACTION_RESTRICT_BACKGROUND_CHANGED)) {
  63. mLog.log("OBSERVED data saver changed");
  64. handleDataSaverChanged();
  65. } else if (action.equals(TetheringNotificationUpdater.ACTION_DISABLE_TETHERING)) {
  66. untetherAll();
  67. }
  68. }
  69. void startTethering(final TetheringRequestParcel request, final IIntResultListener listener) {
  70. mHandler.post(() -> {
  71. final TetheringRequestParcel unfinishedRequest = mActiveTetheringRequests.get(
  72. request.tetheringType);
  73. // If tethering is already enabled with a different request,
  74. // disable before re-enabling.
  75. if (unfinishedRequest != null
  76. && !TetheringUtils.isTetheringRequestEquals(unfinishedRequest, request)) {
  77. enableTetheringInternal(request.tetheringType, false /* disabled */, null);
  78. mEntitlementMgr.stopProvisioningIfNeeded(request.tetheringType);
  79. }
  80. mActiveTetheringRequests.put(request.tetheringType, request);
  81. if (request.exemptFromEntitlementCheck) {
  82. mEntitlementMgr.setExemptedDownstreamType(request.tetheringType);
  83. } else {
  84. mEntitlementMgr.startProvisioningIfNeeded(request.tetheringType,
  85. request.showProvisioningUi);
  86. }
  87. enableTetheringInternal(request.tetheringType, true /* enabled */, listener);
  88. });
  89. }
  90. /**
  91. * Enables or disables tethering for the given type. If provisioning is required, it will
  92. * schedule provisioning rechecks for the specified interface.
  93. */
  94. private void enableTetheringInternal(int type, boolean enable,
  95. final IIntResultListener listener) {
  96. int result = TETHER_ERROR_NO_ERROR;
  97. switch (type) {
  98. case TETHERING_WIFI:
  99. result = setWifiTethering(enable);
  100. break;
  101. case TETHERING_USB:
  102. result = setUsbTethering(enable);
  103. break;
  104. case TETHERING_BLUETOOTH:
  105. setBluetoothTethering(enable, listener);
  106. break;
  107. case TETHERING_NCM:
  108. result = setNcmTethering(enable);
  109. break;
  110. case TETHERING_ETHERNET:
  111. result = setEthernetTethering(enable);
  112. break;
  113. default:
  114. Log.w(TAG, "Invalid tether type.");
  115. result = TETHER_ERROR_UNKNOWN_TYPE;
  116. }
  117. // The result of Bluetooth tethering will be sent by #setBluetoothTethering.
  118. if (type != TETHERING_BLUETOOTH) {
  119. sendTetherResult(listener, result, type);
  120. }
  121. }
  122. private int setWifiTethering(final boolean enable) {
  123. final long ident = Binder.clearCallingIdentity();
  124. try {
  125. synchronized (mPublicSync) {
  126. final WifiManager mgr = getWifiManager();
  127. if (mgr == null) {
  128. mLog.e("setWifiTethering: failed to get WifiManager!");
  129. return TETHER_ERROR_SERVICE_UNAVAIL;
  130. }
  131. if ((enable && mgr.startTetheredHotspot(null /* use existing softap config */))
  132. || (!enable && mgr.stopSoftAp())) {
  133. mWifiTetherRequested = enable;
  134. return TETHER_ERROR_NO_ERROR;
  135. }
  136. }
  137. } finally {
  138. Binder.restoreCallingIdentity(ident);
  139. }
  140. return TETHER_ERROR_INTERNAL_ERROR;
  141. }
  142. }

从构造函数可知,它监听了WifiManager.WIFI_AP_STATE_CHANGED_ACTION AP状态改变的广播,这让它有了在驱动创建成功SoftAp iface后,为它配置IP的能力,这个后面再介绍。根据startTethering()的调用逻辑,发现它调用了 WifiManager.startTetheredHotspot(),WifiManager我们应该很熟悉:

  1. /**
  2. * This class provides the primary API for managing all aspects of Wi-Fi
  3. * connectivity.
  4. * <p>
  5. * On releases before {@link android.os.Build.VERSION_CODES#N}, this object
  6. * should only be obtained from an {@linkplain Context#getApplicationContext()
  7. * application context}, and not from any other derived context to avoid memory
  8. * leaks within the calling process.
  9. * <p>
  10. * It deals with several categories of items:
  11. * </p>
  12. * <ul>
  13. * <li>The list of configured networks. The list can be viewed and updated, and
  14. * attributes of individual entries can be modified.</li>
  15. * <li>The currently active Wi-Fi network, if any. Connectivity can be
  16. * established or torn down, and dynamic information about the state of the
  17. * network can be queried.</li>
  18. * <li>Results of access point scans, containing enough information to make
  19. * decisions about what access point to connect to.</li>
  20. * <li>It defines the names of various Intent actions that are broadcast upon
  21. * any sort of change in Wi-Fi state.
  22. * </ul>
  23. * <p>
  24. * This is the API to use when performing Wi-Fi specific operations. To perform
  25. * operations that pertain to network connectivity at an abstract level, use
  26. * {@link android.net.ConnectivityManager}.
  27. * </p>
  28. */
  29. @SystemService(Context.WIFI_SERVICE)
  30. public class WifiManager {
  31. /**
  32. * Start Soft AP (hotspot) mode for tethering purposes with the specified configuration.
  33. * Note that starting Soft AP mode may disable station mode operation if the device does not
  34. * support concurrency.
  35. * @param softApConfig A valid SoftApConfiguration specifying the configuration of the SAP,
  36. * or null to use the persisted Soft AP configuration that was previously
  37. * set using {@link #setSoftApConfiguration(softApConfiguration)}.
  38. * @return {@code true} if the operation succeeded, {@code false} otherwise
  39. *
  40. * @hide
  41. */
  42. @SystemApi
  43. @RequiresPermission(anyOf = {
  44. android.Manifest.permission.NETWORK_STACK,
  45. NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
  46. })
  47. public boolean startTetheredHotspot(@Nullable SoftApConfiguration softApConfig) {
  48. try {
  49. return mService.startTetheredHotspot(softApConfig);
  50. } catch (RemoteException e) {
  51. throw e.rethrowFromSystemServer();
  52. }
  53. }
  54. }
  55. /**
  56. * WifiService handles remote WiFi operation requests by implementing
  57. * the IWifiManager interface.
  58. */
  59. public class WifiServiceImpl extends BaseWifiService {
  60. /**
  61. * see {@link android.net.wifi.WifiManager#startTetheredHotspot(SoftApConfiguration)}
  62. * @param softApConfig SSID, security and channel details as part of SoftApConfiguration
  63. * @return {@code true} if softap start was triggered
  64. * @throws SecurityException if the caller does not have permission to start softap
  65. */
  66. @Override
  67. public boolean startTetheredHotspot(@Nullable SoftApConfiguration softApConfig) {
  68. // NETWORK_STACK is a signature only permission.
  69. enforceNetworkStackPermission();
  70. mLog.info("startTetheredHotspot uid=%").c(Binder.getCallingUid()).flush();
  71. if (!mTetheredSoftApTracker.setEnablingIfAllowed()) {
  72. mLog.err("Tethering is already active.").flush();
  73. return false;
  74. }
  75. if (!mWifiThreadRunner.call(
  76. () -> mActiveModeWarden.canRequestMoreSoftApManagers(), false)) {
  77. // Take down LOHS if it is up.
  78. mLohsSoftApTracker.stopAll();
  79. }
  80. if (!startSoftApInternal(new SoftApModeConfiguration(
  81. WifiManager.IFACE_IP_MODE_TETHERED, softApConfig,
  82. mTetheredSoftApTracker.getSoftApCapability()))) {
  83. mTetheredSoftApTracker.setFailedWhileEnabling();
  84. return false;
  85. }
  86. return true;
  87. }
  88. /**
  89. * Internal method to start softap mode. Callers of this method should have already checked
  90. * proper permissions beyond the NetworkStack permission.
  91. */
  92. private boolean startSoftApInternal(SoftApModeConfiguration apConfig) {
  93. int uid = Binder.getCallingUid();
  94. boolean privileged = isSettingsOrSuw(Binder.getCallingPid(), uid);
  95. mLog.trace("startSoftApInternal uid=% mode=%")
  96. .c(uid).c(apConfig.getTargetMode()).flush();
  97. // null wifiConfig is a meaningful input for CMD_SET_AP; it means to use the persistent
  98. // AP config.
  99. SoftApConfiguration softApConfig = apConfig.getSoftApConfiguration();
  100. if (softApConfig != null
  101. && (!WifiApConfigStore.validateApWifiConfiguration(softApConfig, privileged)
  102. || !validateSoftApBand(softApConfig.getBand()))) {
  103. Log.e(TAG, "Invalid SoftApConfiguration");
  104. return false;
  105. }
  106. mActiveModeWarden.startSoftAp(apConfig);
  107. return true;
  108. }
  109. }

主要的,首先创建了一个目标共享MODE为WifiManager.IFACE_IP_MODE_TETHERED的SoftApModeConfiguration对象,它描述了我们对开启的热点的配置信息,随后调用ActiveModeWarden.startSoftAp():

  1. /**
  2. * This class provides the implementation for different WiFi operating modes.
  3. */
  4. public class ActiveModeWarden {
  5. /**
  6. * WifiController is the class used to manage wifi state for various operating
  7. * modes (normal, airplane, wifi hotspot, etc.).
  8. */
  9. private class WifiController extends StateMachine {
  10. WifiController() {
  11. super(TAG, mLooper);
  12. DefaultState defaultState = new DefaultState();
  13. addState(defaultState); {
  14. addState(mDisabledState, defaultState);
  15. addState(mEnabledState, defaultState);
  16. }
  17. setLogRecSize(100);
  18. setLogOnlyTransitions(false);
  19. }
  20. @Override
  21. public void start() {
  22. if (shouldEnableSta()) {
  23. startClientModeManager();
  24. setInitialState(mEnabledState);
  25. } else {
  26. setInitialState(mDisabledState);
  27. }
  28. super.start();
  29. }
  30. class DefaultState extends State {
  31. }
  32. class EnabledState extends BaseState {
  33. private boolean mIsDisablingDueToAirplaneMode;
  34. @Override
  35. public void enter() {
  36. log("EnabledState.enter()");
  37. super.enter();
  38. if (!hasAnyModeManager()) {
  39. Log.e(TAG, "Entered EnabledState, but no active mode managers");
  40. }
  41. mIsDisablingDueToAirplaneMode = false;
  42. }
  43. @Override
  44. public void exit() {
  45. log("EnabledState.exit()");
  46. if (hasAnyModeManager()) {
  47. Log.e(TAG, "Existing EnabledState, but has active mode managers");
  48. }
  49. super.exit();
  50. }
  51. @Override
  52. public boolean processMessageFiltered(Message msg) {
  53. switch (msg.what) {
  54. case CMD_WIFI_TOGGLED:
  55. case CMD_SCAN_ALWAYS_MODE_CHANGED:
  56. if (shouldEnableSta()) {
  57. if (hasAnyClientModeManager()) {
  58. switchAllClientModeManagers();
  59. } else {
  60. startClientModeManager();
  61. }
  62. } else {
  63. stopAllClientModeManagers();
  64. }
  65. break;
  66. case CMD_SET_AP:
  67. // note: CMD_SET_AP is handled/dropped in ECM mode - will not start here
  68. if (msg.arg1 == 1) {
  69. startSoftApModeManager((SoftApModeConfiguration) msg.obj);
  70. } else {
  71. stopSoftApModeManagers(msg.arg2);
  72. }
  73. break;
  74. case CMD_AIRPLANE_TOGGLED:
  75. // airplane mode toggled on is handled in the default state
  76. if (mSettingsStore.isAirplaneModeOn()) {
  77. mIsDisablingDueToAirplaneMode = true;
  78. return NOT_HANDLED;
  79. } else {
  80. if (mIsDisablingDueToAirplaneMode) {
  81. // Previous airplane mode toggle on is being processed, defer the
  82. // message toggle off until previous processing is completed.
  83. // Once previous airplane mode toggle is complete, we should
  84. // transition to DisabledState. There, we will process the deferred
  85. // airplane mode toggle message to disable airplane mode.
  86. deferMessage(msg);
  87. } else {
  88. // when airplane mode is toggled off, but wifi is on, we can keep it
  89. // on
  90. log("airplane mode toggled - and airplane mode is off. return "
  91. + "handled");
  92. }
  93. return HANDLED;
  94. }
  95. case CMD_AP_STOPPED:
  96. case CMD_AP_START_FAILURE:
  97. if (!hasAnyModeManager()) {
  98. if (shouldEnableSta()) {
  99. log("SoftAp disabled, start client mode");
  100. startClientModeManager();
  101. } else {
  102. log("SoftAp mode disabled, return to DisabledState");
  103. transitionTo(mDisabledState);
  104. }
  105. } else {
  106. log("AP disabled, remain in EnabledState.");
  107. }
  108. break;
  109. case CMD_STA_START_FAILURE:
  110. case CMD_STA_STOPPED:
  111. // Client mode stopped. Head to Disabled to wait for next command if there
  112. // no active mode managers.
  113. if (!hasAnyModeManager()) {
  114. log("STA disabled, return to DisabledState.");
  115. transitionTo(mDisabledState);
  116. } else {
  117. log("STA disabled, remain in EnabledState.");
  118. }
  119. break;
  120. case CMD_RECOVERY_RESTART_WIFI:
  121. final String bugTitle;
  122. final String bugDetail;
  123. if (msg.arg1 < SelfRecovery.REASON_STRINGS.length && msg.arg1 >= 0) {
  124. bugDetail = SelfRecovery.REASON_STRINGS[msg.arg1];
  125. bugTitle = "Wi-Fi BugReport: " + bugDetail;
  126. } else {
  127. bugDetail = "";
  128. bugTitle = "Wi-Fi BugReport";
  129. }
  130. if (msg.arg1 != SelfRecovery.REASON_LAST_RESORT_WATCHDOG) {
  131. mHandler.post(() -> mClientModeImpl.takeBugReport(bugTitle, bugDetail));
  132. }
  133. log("Recovery triggered, disable wifi");
  134. deferMessage(obtainMessage(CMD_DEFERRED_RECOVERY_RESTART_WIFI));
  135. shutdownWifi();
  136. // onStopped will move the state machine to "DisabledState".
  137. break;
  138. default:
  139. return NOT_HANDLED;
  140. }
  141. return HANDLED;
  142. }
  143. }
  144. class DisabledState extends BaseState {
  145. @Override
  146. public void enter() {
  147. log("DisabledState.enter()");
  148. super.enter();
  149. if (hasAnyModeManager()) {
  150. Log.e(TAG, "Entered DisabledState, but has active mode managers");
  151. }
  152. }
  153. @Override
  154. public void exit() {
  155. log("DisabledState.exit()");
  156. super.exit();
  157. }
  158. @Override
  159. public boolean processMessageFiltered(Message msg) {
  160. switch (msg.what) {
  161. case CMD_WIFI_TOGGLED:
  162. case CMD_SCAN_ALWAYS_MODE_CHANGED:
  163. if (shouldEnableSta()) {
  164. startClientModeManager();
  165. transitionTo(mEnabledState);
  166. }
  167. break;
  168. case CMD_SET_AP:
  169. // note: CMD_SET_AP is handled/dropped in ECM mode - will not start here
  170. if (msg.arg1 == 1) {
  171. startSoftApModeManager((SoftApModeConfiguration) msg.obj);
  172. transitionTo(mEnabledState);
  173. }
  174. break;
  175. case CMD_RECOVERY_RESTART_WIFI:
  176. log("Recovery triggered, already in disabled state");
  177. // intentional fallthrough
  178. case CMD_DEFERRED_RECOVERY_RESTART_WIFI:
  179. // wait mRecoveryDelayMillis for letting driver clean reset.
  180. sendMessageDelayed(CMD_RECOVERY_RESTART_WIFI_CONTINUE,
  181. readWifiRecoveryDelay());
  182. break;
  183. case CMD_RECOVERY_RESTART_WIFI_CONTINUE:
  184. if (shouldEnableSta()) {
  185. startClientModeManager();
  186. transitionTo(mEnabledState);
  187. }
  188. break;
  189. default:
  190. return NOT_HANDLED;
  191. }
  192. return HANDLED;
  193. }
  194. }
  195. }
  196. /** Starts SoftAp. */
  197. public void startSoftAp(SoftApModeConfiguration softApConfig) {
  198. mWifiController.sendMessage(WifiController.CMD_SET_AP, 1, 0, softApConfig);
  199. }
  200. }

经常接触Wifi或者BT Framework框架的打工人应该很熟悉StateMachine的流程了,这里不再介绍相关的流程,只关注开启热点的处理流程,startSoftAp()的操作只是发送了WifiController.CMD_SET_AP命令,让状态机处理开启的流程,假设这是我们第一次开热点,也是只开热点,DisabledState状态处理该cmd:

  1. case CMD_SET_AP:
  2. // note: CMD_SET_AP is handled/dropped in ECM mode - will not start here
  3. if (msg.arg1 == 1) {
  4. startSoftApModeManager((SoftApModeConfiguration) msg.obj);
  5. transitionTo(mEnabledState);
  6. }
  7. /**
  8. * Method to enable soft ap for wifi hotspot.
  9. *
  10. * The supplied SoftApModeConfiguration includes the target softap WifiConfiguration (or null if
  11. * the persisted config is to be used) and the target operating mode (ex,
  12. * {@link WifiManager#IFACE_IP_MODE_TETHERED} {@link WifiManager#IFACE_IP_MODE_LOCAL_ONLY}).
  13. *
  14. * @param softApConfig SoftApModeConfiguration for the hostapd softap
  15. */
  16. private void startSoftApModeManager(@NonNull SoftApModeConfiguration softApConfig) {
  17. Log.d(TAG, "Starting SoftApModeManager config = "
  18. + softApConfig.getSoftApConfiguration());
  19. Preconditions.checkState(softApConfig.getTargetMode() == IFACE_IP_MODE_LOCAL_ONLY
  20. || softApConfig.getTargetMode() == IFACE_IP_MODE_TETHERED);
  21. WifiManager.SoftApCallback callback =
  22. softApConfig.getTargetMode() == IFACE_IP_MODE_LOCAL_ONLY
  23. ? mLohsCallback : mSoftApCallback;
  24. SoftApListener listener = new SoftApListener();
  25. ActiveModeManager manager =
  26. mWifiInjector.makeSoftApManager(listener, callback, softApConfig);
  27. listener.setActiveModeManager(manager);
  28. manager.start();
  29. manager.setRole(getRoleForSoftApIpMode(softApConfig.getTargetMode()));
  30. mActiveModeManagers.add(manager);
  31. }
  32. private @ActiveModeManager.Role int getRoleForSoftApIpMode(int ipMode) {
  33. return ipMode == IFACE_IP_MODE_TETHERED
  34. ? ActiveModeManager.ROLE_SOFTAP_TETHERED : ActiveModeManager.ROLE_SOFTAP_LOCAL_ONLY;
  35. }

创建SoftApManager并调用其start(),因为之前我们创建的MODE是IFACE_IP_MODE_TETHERED所以给SoftApManager set的role这里是ROLE_SOFTAP_TETHERED;随后进入EnabledState。我们看SoftApManager,它是一个管理WiFi AP mode管理类:

  1. /**
  2. * Manage WiFi in AP mode.
  3. * The internal state machine runs under the ClientModeImpl handler thread context.
  4. */
  5. public class SoftApManager implements ActiveModeManager {
  6. /**
  7. * Listener for soft AP events.
  8. */
  9. private final SoftApListener mSoftApListener = new SoftApListener() {
  10. @Override
  11. public void onFailure() {
  12. mStateMachine.sendMessage(SoftApStateMachine.CMD_FAILURE);
  13. }
  14. @Override
  15. public void onConnectedClientsChanged(NativeWifiClient client, boolean isConnected) {
  16. if (client != null) {
  17. mStateMachine.sendMessage(SoftApStateMachine.CMD_ASSOCIATED_STATIONS_CHANGED,
  18. isConnected ? 1 : 0, 0, client);
  19. } else {
  20. Log.e(TAG, "onConnectedClientsChanged: Invalid type returned");
  21. }
  22. }
  23. @Override
  24. public void onSoftApChannelSwitched(int frequency,
  25. @WifiAnnotations.Bandwidth int bandwidth) {
  26. mStateMachine.sendMessage(
  27. SoftApStateMachine.CMD_SOFT_AP_CHANNEL_SWITCHED, frequency, bandwidth);
  28. }
  29. };
  30. public SoftApManager(@NonNull WifiContext context,
  31. @NonNull Looper looper,
  32. @NonNull FrameworkFacade framework,
  33. @NonNull WifiNative wifiNative,
  34. String countryCode,
  35. @NonNull Listener listener,
  36. @NonNull WifiManager.SoftApCallback callback,
  37. @NonNull WifiApConfigStore wifiApConfigStore,
  38. @NonNull SoftApModeConfiguration apConfig,
  39. @NonNull WifiMetrics wifiMetrics,
  40. @NonNull SarManager sarManager,
  41. @NonNull BaseWifiDiagnostics wifiDiagnostics) {
  42. mStateMachine = new SoftApStateMachine(looper);
  43. }
  44. /**
  45. * Start soft AP, as configured in the constructor.
  46. */
  47. @Override
  48. public void start() {
  49. mStateMachine.sendMessage(SoftApStateMachine.CMD_START);
  50. }
  51. private class SoftApStateMachine extends StateMachine {
  52. private final State mIdleState = new IdleState();
  53. private final State mStartedState = new StartedState();
  54. private final InterfaceCallback mWifiNativeInterfaceCallback = new InterfaceCallback() {
  55. @Override
  56. public void onDestroyed(String ifaceName) {
  57. if (mApInterfaceName != null && mApInterfaceName.equals(ifaceName)) {
  58. sendMessage(CMD_INTERFACE_DESTROYED);
  59. }
  60. }
  61. @Override
  62. public void onUp(String ifaceName) {
  63. if (mApInterfaceName != null && mApInterfaceName.equals(ifaceName)) {
  64. sendMessage(CMD_INTERFACE_STATUS_CHANGED, 1);
  65. }
  66. }
  67. @Override
  68. public void onDown(String ifaceName) {
  69. if (mApInterfaceName != null && mApInterfaceName.equals(ifaceName)) {
  70. sendMessage(CMD_INTERFACE_STATUS_CHANGED, 0);
  71. }
  72. }
  73. };
  74. SoftApStateMachine(Looper looper) {
  75. super(TAG, looper);
  76. addState(mIdleState);
  77. addState(mStartedState);
  78. setInitialState(mIdleState);
  79. start();
  80. }
  81. private class IdleState extends State {
  82. }
  83. private class StartedState extends State {
  84. }
  85. }
  86. }

SoftApManager内部包含一个小的状态机SoftApStateMachine,它只有两个状态,Idle状态是初始状态,它处理发来的SoftApStateMachine.CMD_START:

  1. private class IdleState extends State {
  2. @Override
  3. public void enter() {
  4. }
  5. @Override
  6. public boolean processMessage(Message message) {
  7. switch (message.what) {
  8. case CMD_START:
  9. mApInterfaceName = mWifiNative.setupInterfaceForSoftApMode(
  10. mWifiNativeInterfaceCallback);
  11. if (TextUtils.isEmpty(mApInterfaceName)) {
  12. Log.e(TAG, "setup failure when creating ap interface.");
  13. updateApState(WifiManager.WIFI_AP_STATE_FAILED,
  14. WifiManager.WIFI_AP_STATE_DISABLED,
  15. WifiManager.SAP_START_FAILURE_GENERAL);
  16. mWifiMetrics.incrementSoftApStartResult(
  17. false, WifiManager.SAP_START_FAILURE_GENERAL);
  18. mModeListener.onStartFailure();
  19. break;
  20. }
  21. mSoftApNotifier.dismissSoftApShutDownTimeoutExpiredNotification();
  22. updateApState(WifiManager.WIFI_AP_STATE_ENABLING,
  23. WifiManager.WIFI_AP_STATE_DISABLED, 0);
  24. int result = startSoftAp();
  25. if (result != SUCCESS) {
  26. int failureReason = WifiManager.SAP_START_FAILURE_GENERAL;
  27. if (result == ERROR_NO_CHANNEL) {
  28. failureReason = WifiManager.SAP_START_FAILURE_NO_CHANNEL;
  29. } else if (result == ERROR_UNSUPPORTED_CONFIGURATION) {
  30. failureReason = WifiManager
  31. .SAP_START_FAILURE_UNSUPPORTED_CONFIGURATION;
  32. }
  33. updateApState(WifiManager.WIFI_AP_STATE_FAILED,
  34. WifiManager.WIFI_AP_STATE_ENABLING,
  35. failureReason);
  36. stopSoftAp();
  37. mWifiMetrics.incrementSoftApStartResult(false, failureReason);
  38. mModeListener.onStartFailure();
  39. break;
  40. }
  41. transitionTo(mStartedState);
  42. break;
  43. }
  44. }
  45. /**
  46. * Start a soft AP instance as configured.
  47. *
  48. * @return integer result code
  49. */
  50. private int startSoftAp() {
  51. SoftApConfiguration config = mApConfig.getSoftApConfiguration();
  52. if (config == null || config.getSsid() == null) {
  53. Log.e(TAG, "Unable to start soft AP without valid configuration");
  54. return ERROR_GENERIC;
  55. }
  56. Log.d(TAG, "band " + config.getBand() + " iface "
  57. + mApInterfaceName + " country " + mCountryCode);
  58. int result = setMacAddress();
  59. if (result != SUCCESS) {
  60. return result;
  61. }
  62. result = setCountryCode();
  63. if (result != SUCCESS) {
  64. return result;
  65. }
  66. // Make a copy of configuration for updating AP band and channel.
  67. SoftApConfiguration.Builder localConfigBuilder = new SoftApConfiguration.Builder(config);
  68. boolean acsEnabled = mCurrentSoftApCapability.areFeaturesSupported(
  69. SoftApCapability.SOFTAP_FEATURE_ACS_OFFLOAD);
  70. result = ApConfigUtil.updateApChannelConfig(
  71. mWifiNative, mContext.getResources(), mCountryCode, localConfigBuilder, config,
  72. acsEnabled);
  73. if (result != SUCCESS) {
  74. Log.e(TAG, "Failed to update AP band and channel");
  75. return result;
  76. }
  77. if (config.isHiddenSsid()) {
  78. Log.d(TAG, "SoftAP is a hidden network");
  79. }
  80. if (!ApConfigUtil.checkSupportAllConfiguration(config, mCurrentSoftApCapability)) {
  81. Log.d(TAG, "Unsupported Configuration detect! config = " + config);
  82. return ERROR_UNSUPPORTED_CONFIGURATION;
  83. }
  84. if (!mWifiNative.startSoftAp(mApInterfaceName,
  85. localConfigBuilder.build(), mSoftApListener)) {
  86. Log.e(TAG, "Soft AP start failed");
  87. return ERROR_GENERIC;
  88. }
  89. mWifiDiagnostics.startLogging(mApInterfaceName);
  90. mStartTimestamp = FORMATTER.format(new Date(System.currentTimeMillis()));
  91. Log.d(TAG, "Soft AP is started ");
  92. return SUCCESS;
  93. }

主要的:

1、WifiNative.setupInterfaceForSoftApMode():创建一个供AP MODE使用的interface,它的状态由mWifiNativeInterfaceCallback回调管理.

2、SoftApManager.startSoftAp():按配置信息,在HAL/Driver层创建一个管理Soft ap的instance,它的状态由SoftApListener回调管理

如果都调用成功,进入StartedState:

  1. private class StartedState extends State {
  2. private WakeupMessage mSoftApTimeoutMessage;
  3. private void scheduleTimeoutMessage() {
  4. if (!mTimeoutEnabled || mConnectedClients.size() != 0) {
  5. cancelTimeoutMessage();
  6. return;
  7. }
  8. long timeout = mApConfig.getSoftApConfiguration().getShutdownTimeoutMillis();
  9. if (timeout == 0) {
  10. timeout = mDefaultShutDownTimeoutMills;
  11. }
  12. mSoftApTimeoutMessage.schedule(SystemClock.elapsedRealtime()
  13. + timeout);
  14. Log.d(TAG, "Timeout message scheduled, delay = "
  15. + timeout);
  16. }
  17. @Override
  18. public void enter() {
  19. mIfaceIsUp = false;
  20. mIfaceIsDestroyed = false;
  21. onUpChanged(mWifiNative.isInterfaceUp(mApInterfaceName));
  22. Handler handler = mStateMachine.getHandler();
  23. mSoftApTimeoutMessage = new WakeupMessage(mContext, handler,
  24. SOFT_AP_SEND_MESSAGE_TIMEOUT_TAG,
  25. SoftApStateMachine.CMD_NO_ASSOCIATED_STATIONS_TIMEOUT);
  26. mSarManager.setSapWifiState(WifiManager.WIFI_AP_STATE_ENABLED);
  27. Log.d(TAG, "Resetting connected clients on start");
  28. mConnectedClients.clear();
  29. mEverReportMetricsForMaxClient = false;
  30. scheduleTimeoutMessage();
  31. }
  32. }

进入StartedState::enter()时,比较重要的是此时会设置一个默认600000ms(10min)的timeout超时机制,如果此时间段一直没有设备连接该AP,就会自动关闭AP。

整个开启AP的过程都会有对外通知当前AP状态改变的广播发送:

  1. /**
  2. * Update AP state.
  3. *
  4. * @param newState new AP state
  5. * @param currentState current AP state
  6. * @param reason Failure reason if the new AP state is in failure state
  7. */
  8. private void updateApState(int newState, int currentState, int reason) {
  9. mSoftApCallback.onStateChanged(newState, reason);
  10. //send the AP state change broadcast
  11. final Intent intent = new Intent(WifiManager.WIFI_AP_STATE_CHANGED_ACTION);
  12. intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
  13. intent.putExtra(WifiManager.EXTRA_WIFI_AP_STATE, newState);
  14. intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_AP_STATE, currentState);
  15. if (newState == WifiManager.WIFI_AP_STATE_FAILED) {
  16. //only set reason number when softAP start failed
  17. intent.putExtra(WifiManager.EXTRA_WIFI_AP_FAILURE_REASON, reason);
  18. }
  19. intent.putExtra(WifiManager.EXTRA_WIFI_AP_INTERFACE_NAME, mApInterfaceName);
  20. intent.putExtra(WifiManager.EXTRA_WIFI_AP_MODE, mApConfig.getTargetMode());
  21. mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
  22. }

假设我们正常开启了热点,此时也会发送AP开启成功的广播。回到前面介绍Tethering的内容,它内部监听了该广播:

  1. private class StateReceiver extends BroadcastReceiver {
  2. @Override
  3. public void onReceive(Context content, Intent intent) {
  4. final String action = intent.getAction();
  5. if (action == null) return;
  6. if (action.equals(UsbManager.ACTION_USB_STATE)) {
  7. handleUsbAction(intent);
  8. } else if (action.equals(CONNECTIVITY_ACTION)) {
  9. handleConnectivityAction(intent);
  10. } else if (action.equals(WifiManager.WIFI_AP_STATE_CHANGED_ACTION)) {
  11. handleWifiApAction(intent);
  12. } else if (action.equals(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION)) {
  13. handleWifiP2pAction(intent);
  14. } else if (action.equals(Intent.ACTION_CONFIGURATION_CHANGED)) {
  15. mLog.log("OBSERVED configuration changed");
  16. updateConfiguration();
  17. } else if (action.equals(UserManager.ACTION_USER_RESTRICTIONS_CHANGED)) {
  18. mLog.log("OBSERVED user restrictions changed");
  19. handleUserRestrictionAction();
  20. } else if (action.equals(ACTION_RESTRICT_BACKGROUND_CHANGED)) {
  21. mLog.log("OBSERVED data saver changed");
  22. handleDataSaverChanged();
  23. } else if (action.equals(TetheringNotificationUpdater.ACTION_DISABLE_TETHERING)) {
  24. untetherAll();
  25. }
  26. }
  27. private void handleWifiApAction(Intent intent) {
  28. final int curState = intent.getIntExtra(EXTRA_WIFI_AP_STATE, WIFI_AP_STATE_DISABLED);
  29. final String ifname = intent.getStringExtra(EXTRA_WIFI_AP_INTERFACE_NAME);
  30. final int ipmode = intent.getIntExtra(EXTRA_WIFI_AP_MODE, IFACE_IP_MODE_UNSPECIFIED);
  31. synchronized (Tethering.this.mPublicSync) {
  32. switch (curState) {
  33. case WifiManager.WIFI_AP_STATE_ENABLING:
  34. // We can see this state on the way to both enabled and failure states.
  35. break;
  36. case WifiManager.WIFI_AP_STATE_ENABLED:
  37. enableWifiIpServingLocked(ifname, ipmode);
  38. break;
  39. case WifiManager.WIFI_AP_STATE_DISABLING:
  40. // We can see this state on the way to disabled.
  41. break;
  42. case WifiManager.WIFI_AP_STATE_DISABLED:
  43. case WifiManager.WIFI_AP_STATE_FAILED:
  44. default:
  45. disableWifiIpServingLocked(ifname, curState);
  46. break;
  47. }
  48. }
  49. }
  50. }
  51. private void enableWifiIpServingLocked(String ifname, int wifiIpMode) {
  52. // Map wifiIpMode values to IpServer.Callback serving states, inferring
  53. // from mWifiTetherRequested as a final "best guess".
  54. final int ipServingMode;
  55. switch (wifiIpMode) {
  56. case IFACE_IP_MODE_TETHERED:
  57. ipServingMode = IpServer.STATE_TETHERED;
  58. break;
  59. case IFACE_IP_MODE_LOCAL_ONLY:
  60. ipServingMode = IpServer.STATE_LOCAL_ONLY;
  61. break;
  62. default:
  63. mLog.e("Cannot enable IP serving in unknown WiFi mode: " + wifiIpMode);
  64. return;
  65. }
  66. if (!TextUtils.isEmpty(ifname)) {
  67. maybeTrackNewInterfaceLocked(ifname);
  68. changeInterfaceState(ifname, ipServingMode);
  69. } else {
  70. mLog.e(String.format(
  71. "Cannot enable IP serving in mode %s on missing interface name",
  72. ipServingMode));
  73. }
  74. }

根据前面的说明,此处会调用Tethering.enableWifiIpServingLocked(),主要的处理有改变ipServerMode的值为IpServer.STATE_TETHERED,以及如下两个函数:

  1. private void maybeTrackNewInterfaceLocked(final String iface) {
  2. // If we don't care about this type of interface, ignore.
  3. final int interfaceType = ifaceNameToType(iface);
  4. if (interfaceType == TETHERING_INVALID) {
  5. mLog.log(iface + " is not a tetherable iface, ignoring");
  6. return;
  7. }
  8. maybeTrackNewInterfaceLocked(iface, interfaceType);
  9. }
  10. private void maybeTrackNewInterfaceLocked(final String iface, int interfaceType) {
  11. // If we have already started a TISM for this interface, skip.
  12. if (mTetherStates.containsKey(iface)) {
  13. mLog.log("active iface (" + iface + ") reported as added, ignoring");
  14. return;
  15. }
  16. mLog.log("adding TetheringInterfaceStateMachine for: " + iface);
  17. final TetherState tetherState = new TetherState(
  18. new IpServer(iface, mLooper, interfaceType, mLog, mNetd, mBpfCoordinator,
  19. makeControlCallback(), mConfig.enableLegacyDhcpServer,
  20. mConfig.isBpfOffloadEnabled(), mPrivateAddressCoordinator,
  21. mDeps.getIpServerDependencies()));
  22. mTetherStates.put(iface, tetherState);
  23. tetherState.ipServer.start();
  24. }
  25. private void changeInterfaceState(String ifname, int requestedState) {
  26. final int result;
  27. switch (requestedState) {
  28. case IpServer.STATE_UNAVAILABLE:
  29. case IpServer.STATE_AVAILABLE:
  30. result = untether(ifname);
  31. break;
  32. case IpServer.STATE_TETHERED:
  33. case IpServer.STATE_LOCAL_ONLY:
  34. result = tether(ifname, requestedState);
  35. break;
  36. default:
  37. Log.wtf(TAG, "Unknown interface state: " + requestedState);
  38. return;
  39. }
  40. if (result != TETHER_ERROR_NO_ERROR) {
  41. Log.e(TAG, "unable start or stop tethering on iface " + ifname);
  42. return;
  43. }
  44. }

这里两个个函数的内容分别介绍,首先maybeTrackNewInterfaceLocked():

  1. private void maybeTrackNewInterfaceLocked(final String iface, int interfaceType) {
  2. // If we have already started a TISM for this interface, skip.
  3. if (mTetherStates.containsKey(iface)) {
  4. mLog.log("active iface (" + iface + ") reported as added, ignoring");
  5. return;
  6. }
  7. mLog.log("adding TetheringInterfaceStateMachine for: " + iface);
  8. final TetherState tetherState = new TetherState(
  9. new IpServer(iface, mLooper, interfaceType, mLog, mNetd, mBpfCoordinator,
  10. makeControlCallback(), mConfig.enableLegacyDhcpServer,
  11. mConfig.isBpfOffloadEnabled(), mPrivateAddressCoordinator,
  12. mDeps.getIpServerDependencies()));
  13. mTetherStates.put(iface, tetherState);
  14. tetherState.ipServer.start();
  15. }

1、它为每个iface创建了TetherState对象,并保存一个Map里

2、同时创建了IpServer类型实例,并调用了IpServer.start(),它是给AP配置的IP地址的来源

  1. /**
  2. * Provides the interface to IP-layer serving functionality for a given network
  3. * interface, e.g. for tethering or "local-only hotspot" mode.
  4. *
  5. * @hide
  6. */
  7. public class IpServer extends StateMachine {
  8. /** IpServer callback. */
  9. public static class Callback {
  10. /**
  11. * Notify that |who| has changed its tethering state.
  12. *
  13. * @param who the calling instance of IpServer
  14. * @param state one of STATE_*
  15. * @param lastError one of TetheringManager.TETHER_ERROR_*
  16. */
  17. public void updateInterfaceState(IpServer who, int state, int lastError) { }
  18. /**
  19. * Notify that |who| has new LinkProperties.
  20. *
  21. * @param who the calling instance of IpServer
  22. * @param newLp the new LinkProperties to report
  23. */
  24. public void updateLinkProperties(IpServer who, LinkProperties newLp) { }
  25. /**
  26. * Notify that the DHCP leases changed in one of the IpServers.
  27. */
  28. public void dhcpLeasesChanged() { }
  29. /**
  30. * Request Tethering change.
  31. *
  32. * @param tetheringType the downstream type of this IpServer.
  33. * @param enabled enable or disable tethering.
  34. */
  35. public void requestEnableTethering(int tetheringType, boolean enabled) { }
  36. }
  37. private final State mInitialState;
  38. private final State mLocalHotspotState;
  39. private final State mTetheredState;
  40. private final State mUnavailableState;
  41. private final State mWaitingForRestartState;
  42. private LinkAddress mIpv4Address;
  43. // TODO: Add a dependency object to pass the data members or variables from the tethering
  44. // object. It helps to reduce the arguments of the constructor.
  45. public IpServer(
  46. String ifaceName, Looper looper, int interfaceType, SharedLog log,
  47. INetd netd, @NonNull BpfCoordinator coordinator, Callback callback,
  48. boolean usingLegacyDhcp, boolean usingBpfOffload,
  49. PrivateAddressCoordinator addressCoordinator, Dependencies deps) {
  50. mInitialState = new InitialState();
  51. mLocalHotspotState = new LocalHotspotState();
  52. mTetheredState = new TetheredState();
  53. mUnavailableState = new UnavailableState();
  54. mWaitingForRestartState = new WaitingForRestartState();
  55. addState(mInitialState);
  56. addState(mLocalHotspotState);
  57. addState(mTetheredState);
  58. addState(mWaitingForRestartState, mTetheredState);
  59. addState(mUnavailableState);
  60. setInitialState(mInitialState);
  61. }
  62. class InitialState extends State {
  63. }
  64. class BaseServingState extends State {
  65. }
  66. class LocalHotspotState extends BaseServingState{
  67. }
  68. class TetheredState extends BaseServingState {
  69. }
  70. /**
  71. * This state is terminal for the per interface state machine. At this
  72. * point, the master state machine should have removed this interface
  73. * specific state machine from its list of possible recipients of
  74. * tethering requests. The state machine itself will hang around until
  75. * the garbage collector finds it.
  76. */
  77. class UnavailableState extends State {
  78. @Override
  79. public void enter() {
  80. mIpNeighborMonitor.stop();
  81. mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
  82. sendInterfaceState(STATE_UNAVAILABLE);
  83. }
  84. }
  85. class WaitingForRestartState extends State {
  86. @Override
  87. public boolean processMessage(Message message) {
  88. logMessage(this, message.what);
  89. switch (message.what) {
  90. case CMD_TETHER_UNREQUESTED:
  91. transitionTo(mInitialState);
  92. mLog.i("Untethered (unrequested) and restarting " + mIfaceName);
  93. mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
  94. break;
  95. case CMD_INTERFACE_DOWN:
  96. transitionTo(mUnavailableState);
  97. mLog.i("Untethered (interface down) and restarting" + mIfaceName);
  98. mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
  99. break;
  100. default:
  101. return false;
  102. }
  103. return true;
  104. }
  105. }
  106. }

IpServer也是一个小状态机,它主要是计算IP地址并在对应的iface进行地址配置,这样我们ifconfig查看网卡信息时,才能看到配置的信息。IpServer.start()启动之后,处理暂时告一段落.

接着看Tethering.changeInterfaceState():

  1. private void changeInterfaceState(String ifname, int requestedState) {
  2. final int result;
  3. switch (requestedState) {
  4. case IpServer.STATE_UNAVAILABLE:
  5. case IpServer.STATE_AVAILABLE:
  6. result = untether(ifname);
  7. break;
  8. case IpServer.STATE_TETHERED:
  9. case IpServer.STATE_LOCAL_ONLY:
  10. result = tether(ifname, requestedState);
  11. break;
  12. default:
  13. Log.wtf(TAG, "Unknown interface state: " + requestedState);
  14. return;
  15. }
  16. if (result != TETHER_ERROR_NO_ERROR) {
  17. Log.e(TAG, "unable start or stop tethering on iface " + ifname);
  18. return;
  19. }
  20. }

根据前面的Mode,我们进入Tethering.tether():

  1. private int tether(String iface, int requestedState) {
  2. if (DBG) Log.d(TAG, "Tethering " + iface);
  3. synchronized (mPublicSync) {
  4. TetherState tetherState = mTetherStates.get(iface);
  5. if (tetherState == null) {
  6. Log.e(TAG, "Tried to Tether an unknown iface: " + iface + ", ignoring");
  7. return TETHER_ERROR_UNKNOWN_IFACE;
  8. }
  9. // Ignore the error status of the interface. If the interface is available,
  10. // the errors are referring to past tethering attempts anyway.
  11. if (tetherState.lastState != IpServer.STATE_AVAILABLE) {
  12. Log.e(TAG, "Tried to Tether an unavailable iface: " + iface + ", ignoring");
  13. return TETHER_ERROR_UNAVAIL_IFACE;
  14. }
  15. // NOTE: If a CMD_TETHER_REQUESTED message is already in the TISM's queue but not yet
  16. // processed, this will be a no-op and it will not return an error.
  17. //
  18. // This code cannot race with untether() because they both synchronize on mPublicSync.
  19. // TODO: reexamine the threading and messaging model to totally remove mPublicSync.
  20. final int type = tetherState.ipServer.interfaceType();
  21. final TetheringRequestParcel request = mActiveTetheringRequests.get(type, null);
  22. if (request != null) {
  23. mActiveTetheringRequests.delete(type);
  24. }
  25. tetherState.ipServer.sendMessage(IpServer.CMD_TETHER_REQUESTED, requestedState, 0,
  26. request);
  27. return TETHER_ERROR_NO_ERROR;
  28. }
  29. }

主要向IpServer这个StateMachine发送CMD_TETHER_REQUESTED cmd,它的初始状态是InitialState,它处理此消息:

  1. class InitialState extends State {
  2. @Override
  3. public void enter() {
  4. sendInterfaceState(STATE_AVAILABLE);
  5. }
  6. @Override
  7. public boolean processMessage(Message message) {
  8. logMessage(this, message.what);
  9. switch (message.what) {
  10. case CMD_TETHER_REQUESTED:
  11. mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
  12. switch (message.arg1) {
  13. case STATE_LOCAL_ONLY:
  14. maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
  15. transitionTo(mLocalHotspotState);
  16. break;
  17. case STATE_TETHERED:
  18. maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
  19. transitionTo(mTetheredState);
  20. break;
  21. default:
  22. mLog.e("Invalid tethering interface serving state specified.");
  23. }
  24. break;
  25. case CMD_INTERFACE_DOWN:
  26. transitionTo(mUnavailableState);
  27. break;
  28. case CMD_IPV6_TETHER_UPDATE:
  29. updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
  30. break;
  31. default:
  32. return NOT_HANDLED;
  33. }
  34. return HANDLED;
  35. }
  36. }
  37. private void maybeConfigureStaticIp(final TetheringRequestParcel request) {
  38. // Ignore static address configuration if they are invalid or null. In theory, static
  39. // addresses should not be invalid here because TetheringManager do not allow caller to
  40. // specify invalid static address configuration.
  41. if (request == null || request.localIPv4Address == null
  42. || request.staticClientAddress == null || !checkStaticAddressConfiguration(
  43. request.localIPv4Address, request.staticClientAddress)) {
  44. return;
  45. }
  46. mStaticIpv4ServerAddr = request.localIPv4Address;
  47. mStaticIpv4ClientAddr = request.staticClientAddress;
  48. }
  49. // Handling errors in BaseServingState.enter() by transitioning is
  50. // problematic because transitioning during a multi-state jump yields
  51. // a Log.wtf(). Ultimately, there should be only one ServingState,
  52. // and forwarding and NAT rules should be handled by a coordinating
  53. // functional element outside of IpServer.
  54. class TetheredState extends BaseServingState {
  55. @Override
  56. public void enter() {
  57. super.enter();
  58. if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
  59. transitionTo(mInitialState);
  60. }
  61. if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
  62. sendInterfaceState(STATE_TETHERED);
  63. }
  64. @Override
  65. public void exit() {
  66. cleanupUpstream();
  67. super.exit();
  68. }
  69. private void cleanupUpstream() {
  70. if (mUpstreamIfaceSet == null) return;
  71. for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
  72. mUpstreamIfaceSet = null;
  73. clearIpv6ForwardingRules();
  74. }
  75. private void cleanupUpstreamInterface(String upstreamIface) {
  76. // Note that we don't care about errors here.
  77. // Sometimes interfaces are gone before we get
  78. // to remove their rules, which generates errors.
  79. // Just do the best we can.
  80. try {
  81. mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
  82. } catch (RemoteException | ServiceSpecificException e) {
  83. mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
  84. }
  85. try {
  86. mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
  87. } catch (RemoteException | ServiceSpecificException e) {
  88. mLog.e("Exception in disableNat: " + e.toString());
  89. }
  90. }
  91. @Override
  92. public boolean processMessage(Message message) {
  93. if (super.processMessage(message)) return true;
  94. logMessage(this, message.what);
  95. switch (message.what) {
  96. case CMD_TETHER_REQUESTED:
  97. mLog.e("CMD_TETHER_REQUESTED while already tethering.");
  98. break;
  99. case CMD_TETHER_CONNECTION_CHANGED:
  100. final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
  101. if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
  102. if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
  103. break;
  104. }
  105. if (newUpstreamIfaceSet == null) {
  106. cleanupUpstream();
  107. break;
  108. }
  109. for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
  110. cleanupUpstreamInterface(removed);
  111. }
  112. final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
  113. // This makes the call to cleanupUpstream() in the error
  114. // path for any interface neatly cleanup all the interfaces.
  115. mUpstreamIfaceSet = newUpstreamIfaceSet;
  116. for (String ifname : added) {
  117. try {
  118. mNetd.tetherAddForward(mIfaceName, ifname);
  119. mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
  120. } catch (RemoteException | ServiceSpecificException e) {
  121. mLog.e("Exception enabling NAT: " + e.toString());
  122. cleanupUpstream();
  123. mLastError = TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
  124. transitionTo(mInitialState);
  125. return true;
  126. }
  127. }
  128. break;
  129. case CMD_NEIGHBOR_EVENT:
  130. handleNeighborEvent((NeighborEvent) message.obj);
  131. break;
  132. default:
  133. return false;
  134. }
  135. return true;
  136. }
  137. private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
  138. if (mUpstreamIfaceSet == null && newIfaces == null) return true;
  139. if (mUpstreamIfaceSet != null && newIfaces != null) {
  140. return mUpstreamIfaceSet.equals(newIfaces);
  141. }
  142. return false;
  143. }
  144. private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
  145. if (mUpstreamIfaceSet == null) return new HashSet<>();
  146. final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
  147. removed.removeAll(newIfaces.ifnames);
  148. return removed;
  149. }
  150. private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
  151. final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
  152. if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
  153. return added;
  154. }
  155. }
  156. class BaseServingState extends State {
  157. @Override
  158. public void enter() {
  159. if (!startIPv4()) {
  160. mLastError = TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
  161. return;
  162. }
  163. try {
  164. NetdUtils.tetherInterface(mNetd, mIfaceName, asIpPrefix(mIpv4Address));
  165. } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
  166. mLog.e("Error Tethering", e);
  167. mLastError = TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
  168. return;
  169. }
  170. if (!startIPv6()) {
  171. mLog.e("Failed to startIPv6");
  172. // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
  173. return;
  174. }
  175. }
  176. @Override
  177. public void exit() {
  178. // Note that at this point, we're leaving the tethered state. We can fail any
  179. // of these operations, but it doesn't really change that we have to try them
  180. // all in sequence.
  181. stopIPv6();
  182. try {
  183. NetdUtils.untetherInterface(mNetd, mIfaceName);
  184. } catch (RemoteException | ServiceSpecificException e) {
  185. mLastError = TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
  186. mLog.e("Failed to untether interface: " + e);
  187. }
  188. stopIPv4();
  189. resetLinkProperties();
  190. }

maybeConfigureStaticIp()主要是根据传入的config信息初始化一下变量,以便后续配置为设定的static ip;这里假设没有指定IP,直接进入mTetheredState,根据StateMachine的切换逻辑,首先执行父状态的enter(),其中:

  1. /** Internals. */
  2. private boolean startIPv4() {
  3. return configureIPv4(true);
  4. }
  5. private boolean configureIPv4(boolean enabled) {
  6. if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
  7. if (enabled) {
  8. mIpv4Address = requestIpv4Address();
  9. }
  10. if (mIpv4Address == null) {
  11. mLog.e("No available ipv4 address");
  12. return false;
  13. }
  14. if (mInterfaceType == TetheringManager.TETHERING_BLUETOOTH) {
  15. // BT configures the interface elsewhere: only start DHCP.
  16. // TODO: make all tethering types behave the same way, and delete the bluetooth
  17. // code that calls into NetworkManagementService directly.
  18. return configureDhcp(enabled, mIpv4Address, null /* clientAddress */);
  19. }
  20. final IpPrefix ipv4Prefix = asIpPrefix(mIpv4Address);
  21. final Boolean setIfaceUp;
  22. if (mInterfaceType == TetheringManager.TETHERING_WIFI
  23. || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P
  24. || mInterfaceType == TetheringManager.TETHERING_ETHERNET
  25. || mInterfaceType == TetheringManager.TETHERING_WIGIG) {
  26. // The WiFi and Ethernet stack has ownership of the interface up/down state.
  27. // It is unclear whether the Bluetooth or USB stacks will manage their own
  28. // state.
  29. setIfaceUp = null;
  30. } else {
  31. setIfaceUp = enabled;
  32. }
  33. if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
  34. mLog.e("Error configuring interface");
  35. if (!enabled) stopDhcp();
  36. return false;
  37. }
  38. if (enabled) {
  39. mLinkProperties.addLinkAddress(mIpv4Address);
  40. mLinkProperties.addRoute(getDirectConnectedRoute(mIpv4Address));
  41. } else {
  42. mLinkProperties.removeLinkAddress(mIpv4Address);
  43. mLinkProperties.removeRoute(getDirectConnectedRoute(mIpv4Address));
  44. }
  45. return configureDhcp(enabled, mIpv4Address, mStaticIpv4ClientAddr);
  46. }
  47. private LinkAddress requestIpv4Address() {
  48. if (mStaticIpv4ServerAddr != null) return mStaticIpv4ServerAddr;
  49. if (mInterfaceType == TetheringManager.TETHERING_BLUETOOTH) {
  50. return new LinkAddress(BLUETOOTH_IFACE_ADDR);
  51. }
  52. return mPrivateAddressCoordinator.requestDownstreamAddress(this);
  53. }
  54. private boolean configureDhcp(boolean enable, final LinkAddress serverAddr,
  55. final LinkAddress clientAddr) {
  56. if (enable) {
  57. return startDhcp(serverAddr, clientAddr);
  58. } else {
  59. stopDhcp();
  60. return true;
  61. }
  62. }
  63. private boolean startDhcp(final LinkAddress serverLinkAddr, final LinkAddress clientLinkAddr) {
  64. if (mUsingLegacyDhcp) {
  65. return true;
  66. }
  67. final Inet4Address addr = (Inet4Address) serverLinkAddr.getAddress();
  68. final Inet4Address clientAddr = clientLinkAddr == null ? null :
  69. (Inet4Address) clientLinkAddr.getAddress();
  70. final DhcpServingParamsParcel params = makeServingParams(addr /* defaultRouter */,
  71. addr /* dnsServer */, serverLinkAddr, clientAddr);
  72. mDhcpServerStartIndex++;
  73. mDeps.makeDhcpServer(
  74. mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
  75. return true;
  76. }

这里我们没指定static Ip,就会通过requestIpv4Address()函数获取一个随机的IP地址(基本是xxx.xxx.xxx.xxx/netmask),获取到地址后,紧接着就是去设置和通过DHCP为interface配置IP了。

之后就是通过Netd配置iface,因为这类网络共享需要一些路由配置,这部分要由Netd的内部负责处理:

NetdUtils.tetherInterface(mNetd, mIfaceName, asIpPrefix(mIpv4Address));

随后进入TetheredState。

这样SoftAp的开启的流程就粗略的过了一遍,至于大家工作中有跟其他细致流程相关的,可以根据这个流程进行自己的开发与分析了。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/287199
推荐阅读
相关标签
  

闽ICP备14008679号