Android-系统服务-WifiManager

本文详细介绍了Android中Wi-Fi相关的权限与接口,包括ACCESS_WIFI_STATE、CHANGE_WIFI_STATE等权限的作用与保护级别,以及WifiManager类中用于控制Wi-Fi状态的方法如setWifiEnabled等,并提供了代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

0 快速索引表

  • 权限汇总

https://developer.android.google.cn/reference/android/Manifest.permission

/frameworks/base/core/res/AndroidManifest.xml

android.permission.ACCESS_WIFI_STATE

android.permission.CHANGE_WIFI_STATE

android.permission.LOCAL_MAC_ADDRESS

android.permission.ACCESS_FINE_LOCATION

  • 接口 汇总(5个)

https://developer.android.google.cn/reference/android/net/wifi/WifiManager

/packages/modules/Wifi/framework/java/android/net/wifi/WifiManager.java

android.net.wifi.WifiManager.setWifiEnabled

android.net.wifi.WifiManager.disableNetwork

android.net.wifi.WifiManager.enableNetwork

android.net.wifi.WifiManager.getWifiState

https://developer.android.google.cn/reference/android/net/wifi/WifiInfo

/packages/modules/Wifi/framework/java/android/net/wifi/WifiInfo.java

android.net.wifi.WifiInfo.getMacAddress

android.net.wifi.WifiInfo.getBSSID

  • adb shell svc wifi 命令汇总

adb shell svc wifi disable

adb shell svc wifi enable

  • adb shell cmd wifi 命令汇总

adb shell cmd wifi status

adb shell cmd wifi set-wifi-enabled disabled

adb shell cmd wifi set-wifi-enabled  enabled

  • adb shell dumpsys appops 命令汇总

adb shell dumpsys appops --op WIFI_SCAN

adb shell dumpsys appops --op CHANGE_WIFI_STATE


1 需求

  • 打开Wi-Fi
  • 关闭Wi-Fi
  • 获取Wi-Fi的MAC地址

2 权限

android.permission.ACCESS_WIFI_STATE

  • Added in API level 1
  • Protection level: normal
1982     <!-- Allows applications to access information about Wi-Fi networks.
1983          <p>Protection level: normal
1984     -->
1985     <permission android:name="android.permission.ACCESS_WIFI_STATE"
1986         android:description="@string/permdesc_accessWifiState"
1987         android:label="@string/permlab_accessWifiState"
1988         android:protectionLevel="normal" />

android.permission.CHANGE_WIFI_STATE

  • Added in API level 1
  • Protection level: normal
1990     <!-- Allows applications to change Wi-Fi connectivity state.
1991          <p>Protection level: normal
1992     -->
1993     <permission android:name="android.permission.CHANGE_WIFI_STATE"
1994         android:description="@string/permdesc_changeWifiState"
1995         android:label="@string/permlab_changeWifiState"
1996         android:protectionLevel="normal" />

android.permission.LOCAL_MAC_ADDRESS

5844     <!-- @SystemApi Allows applications to read the local WiFi and Bluetooth MAC address.
5845         @hide -->
5846     <permission android:name="android.permission.LOCAL_MAC_ADDRESS"
5847                 android:protectionLevel="signature|privileged" />
5848     <uses-permission android:name="android.permission.LOCAL_MAC_ADDRESS"/>

android.permission.ACCESS_FINE_LOCATION

1210     <!-- Allows an app to access precise location.
1211          Alternatively, you might want {@link #ACCESS_COARSE_LOCATION}.
1212          <p>Protection level: dangerous
1213     -->
1214     <permission android:name="android.permission.ACCESS_FINE_LOCATION"
1215         android:permissionGroup="android.permission-group.UNDEFINED"
1216         android:label="@string/permlab_accessFineLocation"
1217         android:description="@string/permdesc_accessFineLocation"
1218         android:backgroundPermission="android.permission.ACCESS_BACKGROUND_LOCATION"
1219         android:protectionLevel="dangerous|instant" />

3 接口

android.net.wifi.WifiManager.setWifiEnabled

  • Added in API level 1
  • Deprecated in API level 29
  • 8.0:无权限要求
  • 8.1:CHANGE_WIFI_STATE权限,protectionLevel是normal
  • 10:接口废弃,10及以后返回false;9及以前正常

4074      /**
4075       * Enable or disable Wi-Fi.
4076       * <p>
4077       * Applications must have the {@link android.Manifest.permission#CHANGE_WIFI_STATE}
4078       * permission to toggle wifi.
4079       *
4080       * @param enabled {@code true} to enable, {@code false} to disable.
4081       * @return {@code false} if the request cannot be satisfied; {@code true} indicates that wifi is
4082       *         either already in the requested state, or in progress toward the requested state.
4083       * @throws  {@link java.lang.SecurityException} if the caller is missing required permissions.
4084       *
4085       * @deprecated Starting with Build.VERSION_CODES#Q, applications are not allowed to
4086       * enable/disable Wi-Fi.
4087       * <b>Compatibility Note:</b> For applications targeting
4088       * {@link android.os.Build.VERSION_CODES#Q} or above, this API will always fail and return
4089       * {@code false}. If apps are targeting an older SDK ({@link android.os.Build.VERSION_CODES#P}
4090       * or below), they can continue to use this API.
4091       * <p>
4092       * Deprecation Exemptions:
4093       * <ul>
4094       * <li>Device Owner (DO), Profile Owner (PO) and system apps.
4095       * </ul>
4096       *
4097       * Starting with Build.VERSION_CODES#T, DO/COPE may set a user restriction
4098       * (DISALLOW_CHANGE_WIFI_STATE) to only allow DO/PO to use this API.
4099       */
4100      @Deprecated
4101      public boolean setWifiEnabled(boolean enabled) {
4102          try {
4103              return mService.setWifiEnabled(mContext.getOpPackageName(), enabled);
4104          } catch (RemoteException e) {
4105              throw e.rethrowFromSystemServer();
4106          }
4107      }

android.net.wifi.WifiManager.disableNetwork

  • Added in API level 1
  • Deprecated in API level 29
2958      /**
2959       * Disable a configured network. The specified network will not be
2960       * a candidate for associating. This may result in the asynchronous
2961       * delivery of state change events.
2962       *
2963       * Applications are not allowed to disable networks created by other
2964       * applications.
2965       *
2966       * @param netId the ID of the network as returned by {@link #addNetwork} or {@link
2967       *        #getConfiguredNetworks}.
2968       * @return {@code true} if the operation succeeded
2969       *
2970       * @deprecated
2971       * a) See {@link WifiNetworkSpecifier.Builder#build()} for new
2972       * mechanism to trigger connection to a Wi-Fi network.
2973       * b) See {@link #addNetworkSuggestions(List)},
2974       * {@link #removeNetworkSuggestions(List)} for new API to add Wi-Fi networks for consideration
2975       * when auto-connecting to wifi.
2976       * <b>Compatibility Note:</b> For applications targeting
2977       * {@link android.os.Build.VERSION_CODES#Q} or above, this API will always fail and return
2978       * {@code false}.
2979       * <p>
2980       * Deprecation Exemptions:
2981       * <ul>
2982       * <li>Device Owner (DO), Profile Owner (PO) and system apps.
2983       * </ul>
2984       */
2985      @Deprecated
2986      public boolean disableNetwork(int netId) {
2987          try {
2988              return mService.disableNetwork(netId, mContext.getOpPackageName());
2989          } catch (RemoteException e) {
2990              throw e.rethrowFromSystemServer();
2991          }
2992      }

android.net.wifi.WifiManager.enableNetwork

  • Added in API level 1
  • Deprecated in API level 29
2909      /**
2910       * Allow a previously configured network to be associated with. If
2911       * <code>attemptConnect</code> is true, an attempt to connect to the selected
2912       * network is initiated. This may result in the asynchronous delivery
2913       * of state change events.
2914       * <p>
2915       * <b>Note:</b> Network communication may not use Wi-Fi even if Wi-Fi is connected;
2916       * traffic may instead be sent through another network, such as cellular data,
2917       * Bluetooth tethering, or Ethernet. For example, traffic will never use a
2918       * Wi-Fi network that does not provide Internet access (e.g. a wireless
2919       * printer), if another network that does offer Internet access (e.g.
2920       * cellular data) is available. Applications that need to ensure that their
2921       * network traffic uses Wi-Fi should use APIs such as
2922       * {@link Network#bindSocket(java.net.Socket)},
2923       * {@link Network#openConnection(java.net.URL)}, or
2924       * {@link ConnectivityManager#bindProcessToNetwork} to do so.
2925       *
2926       * Applications are not allowed to enable networks created by other
2927       * applications.
2928       *
2929       * @param netId the ID of the network as returned by {@link #addNetwork} or {@link
2930       *        #getConfiguredNetworks}.
2931       * @param attemptConnect The way to select a particular network to connect to is specify
2932       *        {@code true} for this parameter.
2933       * @return {@code true} if the operation succeeded
2934       *
2935       * @deprecated
2936       * a) See {@link WifiNetworkSpecifier.Builder#build()} for new
2937       * mechanism to trigger connection to a Wi-Fi network.
2938       * b) See {@link #addNetworkSuggestions(List)},
2939       * {@link #removeNetworkSuggestions(List)} for new API to add Wi-Fi networks for consideration
2940       * when auto-connecting to wifi.
2941       * <b>Compatibility Note:</b> For applications targeting
2942       * {@link android.os.Build.VERSION_CODES#Q} or above, this API will always fail and return
2943       * {@code false}.
2944       * Deprecation Exemptions:
2945       * <ul>
2946       * <li>Device Owner (DO), Profile Owner (PO) and system apps.
2947       * </ul>
2948       */
2949      @Deprecated
2950      public boolean enableNetwork(int netId, boolean attemptConnect) {
2951          try {
2952              return mService.enableNetwork(netId, attemptConnect, mContext.getOpPackageName());
2953          } catch (RemoteException e) {
2954              throw e.rethrowFromSystemServer();
2955          }
2956      }

android.net.wifi.WifiManager.getWifiState

  • Added in API level 1
4273      /**
4274       * Gets the Wi-Fi enabled state.
4275       * @return One of {@link #WIFI_STATE_DISABLED},
4276       *         {@link #WIFI_STATE_DISABLING}, {@link #WIFI_STATE_ENABLED},
4277       *         {@link #WIFI_STATE_ENABLING}, {@link #WIFI_STATE_UNKNOWN}
4278       * @see #isWifiEnabled()
4279       */
4280      public int getWifiState() {
4281          try {
4282              return mService.getWifiEnabledState();
4283          } catch (RemoteException e) {
4284              throw e.rethrowFromSystemServer();
4285          }
4286      }

android.net.wifi.WifiInfo.getMacAddress

  • Added in API level 1
  • 权限
    • android.permission.LOCAL_MAC_ADDRESS
    • android.permission.ACCESS_FINE_LOCATION
1079      /**
1080       * Returns the MAC address used for this connection.
1081       * @return MAC address of the connection or {@code "02:00:00:00:00:00"} if the caller has
1082       * insufficient permission.
1083       *
1084       * Requires {@code android.Manifest.permission#LOCAL_MAC_ADDRESS} and
1085       * {@link android.Manifest.permission#ACCESS_FINE_LOCATION}.
1086       */
1087      public String getMacAddress() {
1088          return mMacAddress;
1089      }

android.net.wifi.WifiInfo.getBSSID

  •  Added in API level 1
851      /**
852       * Return the basic service set identifier (BSSID) of the current access point.
853       * <p>
854       * The BSSID may be
855       * <lt>{@code null}, if there is no network currently connected.</lt>
856       * <lt>{@code "02:00:00:00:00:00"}, if the caller has insufficient permissions to access the
857       * BSSID.<lt>
858       * </p>
859       *
860       * @return the BSSID, in the form of a six-byte MAC address: {@code XX:XX:XX:XX:XX:XX}
861       */
862      public String getBSSID() {
863          return mBSSID;
864      }

4 示例

                // 更改 Wi-Fi 状态
                WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
                if (wifiManager.isWifiEnabled()) {
                    wifiManager.setWifiEnabled(false);
                } else {
                    wifiManager.setWifiEnabled(true);
                }

                // Wi-Fi MAC地址
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                Log.i(TAG, "onClick: " + wifiInfo.getMacAddress());

5 adb shell svc wifi

adb shell svc help

adb shell svc wifi -h

 


6 adb shell cmd wifi 命令

adb shell ls /system/bin | findstr wifi

adb shell cmd -l | findstr wifi

adb shell cmd wifi -h


7 adb shell dumpsys appops

adb shell dumpsys appops --op WIFI_SCAN

  • APP_OP_WIFI_SCAN = 10;
  • android.Manifest.permission.ACCESS_WIFI_STATE,

adb shell dumpsys appops --op CHANGE_WIFI_STATE

  • APP_OP_CHANGE_WIFI_STATE = 71;
  •  Manifest.permission.CHANGE_WIFI_STATE,

参考资料

enums.proto - OpenGrok cross reference for /frameworks/proto_logging/stats/enums/app/enums.proto

AppOpsManager.java - OpenGrok cross reference for /frameworks/base/core/java/android/app/AppOpsManager.java


8 参考资料(权限)

https://developer.android.google.cn/reference/android/Manifest.permission

/frameworks/base/core/res/AndroidManifest.xml


参考资料(接口)

https://developer.android.google.cn/reference/android/net/wifi/WifiManager

/packages/modules/Wifi/framework/java/android/net/wifi/WifiManager.java

https://developer.android.google.cn/reference/android/net/wifi/WifiInfo

/packages/modules/Wifi/framework/java/android/net/wifi/WifiInfo.java


参考资料(指南)

WLAN 扫描功能概览  |  Android 开发者  |  Android Developers

唯一标识符最佳做法  |  Android 开发者  |  Android Developers

Android 10 功能和 API  |  Android 开发者  |  Android Developers

以 Android 10 或更高版本为目标平台的应用无法启用或停用 WLAN。WifiManager.setWifiEnabled()方法始终返回 false。

如果您需要提示用户启用或停用 WLAN,请使用设置面板。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值