当前位置:   article > 正文

Android源码笔记--网络(二)

Android源码笔记--网络(二)

           这一节主要了解ConnectivityService,这个api在Android网络里使用较常见,它是Android网络管理的中心,它是在SystemServer中创建的,代码如下:

  1. /frameworks/base/services/java/com/android/server/SystemServer.java
  2. /**
  3. * Starts a miscellaneous grab bag of stuff that has yet to be refactored and organized.
  4. */
  5. private void startOtherServices(@NonNull TimingsTraceAndSlog t) {
  6. try {
  7. connectivity = new ConnectivityService(
  8. context, networkManagement, networkStats, networkPolicy);
  9. ServiceManager.addService(Context.CONNECTIVITY_SERVICE, connectivity,
  10. /* allowIsolated= */ false,
  11. DUMP_FLAG_PRIORITY_HIGH | DUMP_FLAG_PRIORITY_NORMAL);
  12. networkPolicy.bindConnectivityManager(connectivity);
  13. } catch (Throwable e) {
  14. reportWtf("starting Connectivity Service", e);
  15. }
  16. }

分析:初始化过程ConnectivityService的构造方法非常长,如下:

  1. @VisibleForTesting
  2. protected ConnectivityService(Context context, INetworkManagementService netManager,
  3. INetworkStatsService statsService, INetworkPolicyManager policyManager,
  4. IDnsResolver dnsresolver, IpConnectivityLog logger, INetd netd, Dependencies deps) {
  5. if (DBG) log("ConnectivityService starting up");
  6. ...
  7. mDefaultRequest = createDefaultInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
  8. mNetworkRanker = new NetworkRanker();
  9. NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
  10. mNetworkRequests.put(mDefaultRequest, defaultNRI);
  11. mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
  12. mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
  13. NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
  14. ...
  15. mDefaultWifiRequest = createDefaultInternetRequestForTransport(
  16. NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
  17. mHandlerThread = mDeps.makeHandlerThread();
  18. mHandlerThread.start();
  19. mHandler = new InternalHandler(mHandlerThread.getLooper());
  20. mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
  21. mConnectivityDiagnosticsHandler =
  22. new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
  23. mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
  24. Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
  25. mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
  26. mNMS = Objects.requireNonNull(netManager, "missing INetworkManagementService");
  27. mStatsService = Objects.requireNonNull(statsService, "missing INetworkStatsService");
  28. mPolicyManager = Objects.requireNonNull(policyManager, "missing INetworkPolicyManager");
  29. mPolicyManagerInternal = Objects.requireNonNull(
  30. LocalServices.getService(NetworkPolicyManagerInternal.class),
  31. "missing NetworkPolicyManagerInternal");
  32. mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
  33. mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
  34. mNetd = netd;
  35. mKeyStore = KeyStore.getInstance();
  36. mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
  37. mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
  38. mLocationPermissionChecker = new LocationPermissionChecker(mContext);
  39. ...
  40. try {
  41. mPolicyManager.registerListener(mPolicyListener);
  42. } catch (RemoteException e) {
  43. // ouch, no rules updates means some processes may never get network
  44. loge("unable to register INetworkPolicyListener" + e);
  45. }
  46. final PowerManager powerManager = (PowerManager) context.getSystemService(
  47. Context.POWER_SERVICE);
  48. mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
  49. mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
  50. com.android.internal.R.integer.config_networkTransitionTimeout);
  51. mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
  52. mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
  53. ...
  54. boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
  55. log("wifiOnly=" + wifiOnly);
  56. String[] naStrings = context.getResources().getStringArray(
  57. com.android.internal.R.array.networkAttributes);
  58. for (String naString : naStrings) {
  59. try {
  60. NetworkConfig n = new NetworkConfig(naString);
  61. if (VDBG) log("naString=" + naString + " config=" + n);
  62. if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
  63. continue;
  64. }
  65. if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
  66. continue;
  67. }
  68. if (mNetConfigs[n.type] != null) {
  69. continue;
  70. }
  71. mLegacyTypeTracker.addSupportedType(n.type);
  72. mNetConfigs[n.type] = n;
  73. mNetworksDefined++;
  74. } catch(Exception e) {
  75. // ignore it - leave the entry null
  76. }
  77. }
  78. if (mNetConfigs[TYPE_VPN] == null) {
  79. mLegacyTypeTracker.addSupportedType(TYPE_VPN);
  80. mNetworksDefined++; // used only in the log() statement below.
  81. }
  82. ...
  83. if (mNetConfigs[TYPE_ETHERNET] == null && mDeps.hasService(Context.ETHERNET_SERVICE)) {
  84. mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
  85. mNetworksDefined++;
  86. }
  87. if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
  88. mProtectedNetworks = new ArrayList<Integer>();
  89. int[] protectedNetworks = context.getResources().getIntArray(
  90. com.android.internal.R.array.config_protectedNetworks);
  91. for (int p : protectedNetworks) {
  92. if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
  93. mProtectedNetworks.add(p);
  94. } else {
  95. if (DBG) loge("Ignoring protectedNetwork " + p);
  96. }
  97. }
  98. mWolSupportedInterfaces = new ArraySet(
  99. mContext.getResources().getStringArray(
  100. com.android.internal.R.array.config_wakeonlan_supported_interfaces));
  101. mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
  102. mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
  103. ...
  104. IntentFilter intentFilter = new IntentFilter();
  105. intentFilter.addAction(Intent.ACTION_USER_STARTED);
  106. intentFilter.addAction(Intent.ACTION_USER_STOPPED);
  107. intentFilter.addAction(Intent.ACTION_USER_ADDED);
  108. intentFilter.addAction(Intent.ACTION_USER_REMOVED);
  109. intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
  110. mContext.registerReceiverAsUser(
  111. mIntentReceiver,
  112. UserHandle.ALL,
  113. intentFilter,
  114. null /* broadcastPermission */,
  115. mHandler);
  116. mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
  117. new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
  118. // Listen to package add and removal events for all users.
  119. intentFilter = new IntentFilter();
  120. intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
  121. intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
  122. intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
  123. intentFilter.addDataScheme("package");
  124. mContext.registerReceiverAsUser(
  125. mIntentReceiver,
  126. UserHandle.ALL,
  127. intentFilter,
  128. null /* broadcastPermission */,
  129. mHandler);
  130. try {
  131. mNMS.registerObserver(mDataActivityObserver);
  132. } catch (RemoteException e) {
  133. loge("Error registering observer :" + e);
  134. }
  135. mSettingsObserver = new SettingsObserver(mContext, mHandler);
  136. registerSettingsCallbacks();
  137. final DataConnectionStats dataConnectionStats = new DataConnectionStats(mContext, mHandler);
  138. dataConnectionStats.startMonitoring();
  139. mKeepaliveTracker = new KeepaliveTracker(mContext, mHandler);
  140. mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
  141. mContext.getSystemService(NotificationManager.class));
  142. final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
  143. Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
  144. LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
  145. final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
  146. Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
  147. LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
  148. mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
  149. mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
  150. mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
  151. mMultinetworkPolicyTracker.start();
  152. mMultipathPolicyTracker = new MultipathPolicyTracker(mContext, mHandler);
  153. mDnsManager = new DnsManager(mContext, mDnsResolver, mSystemProperties);
  154. registerPrivateDnsSettingsCallbacks();
  155. }

执行过程大体如下:

     (1)创建处理消息的线程并启动。
  (2)创建处理消息的Handle对象mHandler、mTrackerHandler。
  (3)创建DefaultNetworkFactory 对象,用来创建各种NetworkStateTracker对象。
  (4)使用Android的ID设置net.hostname属性。这个属性将作为网络传输中的主机名。
  (5)从Setting 中或者系统资源Config.xml 的config_default_dns_server 项中得到DNS 服务器的IP地址,保存到变量mDefaultDns 中。
  (6)保存对其他系统服务的引用,包括NetworkManagementService、NetworkPolicyManagerService、PowerManagerService 和 PhoneInterfaceManager。
  (7)创建 wakelock对象mNetTransitionWakeLock,在网络有数据传输时用来防止休眠。
  (8)创建NetworkStateTracker对象的数组。
   (9)从系统资源Config.xml读取RadioAttributes、networkAttributes、config_protectedNetworks数组的值,分别用来初始化数组变量mRadioAttributes、mNetConfigs和mProtectedNetworks。
  (10)根据mNetConfigs数组,计算各种网络类型的优先级,保存在mPriorityList列表中。
  (11)变量mNetworkPreference表示系统中优先使用的网络,如果用户在Setting程序中设置了优先网络,则使用用户设置的值;用户没有设置,则从mPriorityList列表按照从先到后的顺序
  挑选当前有效的网络类型。
  (12)创建各种网络连接的NetworkState Tracker对象,填充mNetTrackers数组。
  (13)创建Tethering对象mTethering,用来共享网络。
  (14)创建监听用户状态变化 Intent的Receiver对象。
  (15)创建Nat464Xlat对象mClat,用于IPV4和IPV6地址的转换。

网络经常会用到的场景是获取当前网络类型,一般使用如下:

  1. public static int getNetworkState(Context context) {
  2. ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // 获取网络服务
  3. if (null == connManager) { // 为空则认为无网络
  4. return NETWORK_NONE;
  5. }
  6. // 获取网络类型,如果为空,返回无网络
  7. NetworkInfo activeNetInfo = connManager.getActiveNetworkInfo();
  8. if (activeNetInfo == null || !activeNetInfo.isAvailable()) {
  9. return NETWORK_NONE;
  10. }
  11. return activeNetInfo.getType();
  12. }

看看源码:

  1. /frameworks/base/core/java/android/net/ConnectivityManager.java
  2. private final IConnectivityManager mService;
  3. @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
  4. @Nullable
  5. public Network getActiveNetwork() {
  6. try {
  7. return mService.getActiveNetwork();
  8. } catch (RemoteException e) {
  9. throw e.rethrowFromSystemServer();
  10. }
  11. }
  1. /frameworks/base/core/java/android/net/IConnectivityManager.aidl
  2. interface IConnectivityManager
  3. {
  4. Network getActiveNetwork();
  5. Network getActiveNetworkForUid(int uid, boolean ignoreBlocked);
  6. @UnsupportedAppUsage
  7. NetworkInfo getActiveNetworkInfo();
  8. NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked);
  9. @UnsupportedAppUsage(maxTargetSdk = 28)
  10. NetworkInfo getNetworkInfo(int networkType);
  11. }
  1. /frameworks/base/services/core/java/com/android/server/ConnectivityService.java
  2. @Override
  3. public NetworkInfo getNetworkInfo(int networkType) {
  4. enforceAccessPermission();
  5. final int uid = Binder.getCallingUid();
  6. if (getVpnUnderlyingNetworks(uid) != null) {
  7. // A VPN is active, so we may need to return one of its underlying networks. This
  8. // information is not available in LegacyTypeTracker, so we have to get it from
  9. // getUnfilteredActiveNetworkState.
  10. final NetworkState state = getUnfilteredActiveNetworkState(uid);
  11. if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
  12. filterNetworkStateForUid(state, uid, false);
  13. return state.networkInfo;
  14. }
  15. }
  16. final NetworkState state = getFilteredNetworkState(networkType, uid);
  17. return state.networkInfo;
  18. }
  19. private NetworkState getFilteredNetworkState(int networkType, int uid) {
  20. if (mLegacyTypeTracker.isTypeSupported(networkType)) {
  21. final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
  22. final NetworkState state;
  23. if (nai != null) {
  24. state = nai.getNetworkState();
  25. state.networkInfo.setType(networkType);
  26. } else {
  27. final NetworkInfo info = new NetworkInfo(networkType, 0,
  28. getNetworkTypeName(networkType), "");
  29. info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
  30. info.setIsAvailable(true);
  31. final NetworkCapabilities capabilities = new NetworkCapabilities();
  32. capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
  33. !info.isRoaming());
  34. state = new NetworkState(info, new LinkProperties(), capabilities,
  35. null, null, null);
  36. }
  37. filterNetworkStateForUid(state, uid, false);
  38. return state;
  39. } else {
  40. return NetworkState.EMPTY;
  41. }
  42. }
  1. /frameworks/base/core/java/android/net/LinkProperties.java
  2. //网络连接相关属性在此设置
  3. public final class LinkProperties implements Parcelable {
  4. @TestApi
  5. public LinkProperties(@Nullable LinkProperties source, boolean parcelSensitiveFields) {
  6. mParcelSensitiveFields = parcelSensitiveFields;
  7. if (source == null) return;
  8. mIfaceName = source.mIfaceName;
  9. mLinkAddresses.addAll(source.mLinkAddresses);
  10. mDnses.addAll(source.mDnses);
  11. mValidatedPrivateDnses.addAll(source.mValidatedPrivateDnses);
  12. mUsePrivateDns = source.mUsePrivateDns;
  13. mPrivateDnsServerName = source.mPrivateDnsServerName;
  14. mPcscfs.addAll(source.mPcscfs);
  15. mDomains = source.mDomains;
  16. mRoutes.addAll(source.mRoutes);
  17. mHttpProxy = (source.mHttpProxy == null) ? null : new ProxyInfo(source.mHttpProxy);
  18. for (LinkProperties l: source.mStackedLinks.values()) {
  19. addStackedLink(l);
  20. }
  21. setMtu(source.mMtu);
  22. setDhcpServerAddress(source.getDhcpServerAddress());
  23. mTcpBufferSizes = source.mTcpBufferSizes;
  24. mNat64Prefix = source.mNat64Prefix;
  25. mWakeOnLanSupported = source.mWakeOnLanSupported;
  26. mCaptivePortalApiUrl = source.mCaptivePortalApiUrl;
  27. mCaptivePortalData = source.mCaptivePortalData;
  28. }
  29. }

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

闽ICP备14008679号