• Android app应用连接WiFi的方法(兼容Android10)


    Android应用开发有时候会有应用直连app的需求,由于Android系统 api会时常变动,wifi连接api亦如此,Android10以下直接使用:

    1. WifiConfiguration configured = isExist(ssid);
    2. if (configured != null) {
    3. //在配置表中找到了,直接连接
    4. isSuccess = wifiManager.enableNetwork(configured.networkId, true);
    5. } else {
    6. WifiConfiguration wifiConfig = createWifiConfig(ssid, password, getCipherType(scanResult.getCapabilities()));
    7. int netId = wifiManager.addNetwork(wifiConfig);
    8. isSuccess = wifiManager.enableNetwork(netId, true);
    9. }

    Android 10以上则可以使用

    1. WifiNetworkSpecifier wifiNetworkSpecifier = new WifiNetworkSpecifier.Builder()
    2. .setSsid(ssid)
    3. .setWpa2Passphrase(password)
    4. .build();
    5. //网络请求
    6. NetworkRequest request = new NetworkRequest.Builder()
    7. .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
    8. .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
    9. .addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
    10. .addCapability(NetworkCapabilities.NET_CAPABILITY_TRUSTED)
    11. .setNetworkSpecifier(wifiNetworkSpecifier)
    12. .build();
    13. //网络回调处理
    14. ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
    15. @Override
    16. public void onAvailable(@NonNull Network network) {
    17. super.onAvailable(network);
    18. if (wifiConnectCallback != null) {
    19. wifiConnectCallback.onSuccess(network);
    20. Log.d("WifiUtils", "======onAvailable: ====连接成功======");
    21. }
    22. }
    23. @Override
    24. public void onUnavailable() {
    25. super.onUnavailable();
    26. Log.d("WifiUtils", "======onAvailable: ====连接失败======");
    27. if (wifiConnectCallback != null) {
    28. wifiConnectCallback.onFailure();
    29. }
    30. }
    31. };
    32. //连接网络
    33. connectivityManager.requestNetwork(request, networkCallback);

    或是WifiNetworkSuggestion 方式

    1. WifiNetworkSuggestion suggestion = new WifiNetworkSuggestion.Builder()
    2. .setSsid(ssid)
    3. .setWpa2Passphrase(password)
    4. .setIsAppInteractionRequired(true)
    5. .build();

    最后分享工具类

    1. public class ConnectWifiUtils {
    2. private static final String TAG = ConnectWifiUtils.class.getSimpleName();
    3. private final ConnectivityManager connectivityManager;//连接管理者
    4. private final WifiManager wifiManager;//Wifi管理者
    5. private WifiConnectCallback wifiConnectCallback;
    6. @SuppressLint("StaticFieldLeak")
    7. private static volatile ConnectWifiUtils mInstance;
    8. private final Context mContext;
    9. public ConnectWifiUtils(Context context) {
    10. mContext = context;
    11. wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
    12. connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    13. }
    14. public static ConnectWifiUtils initialize(Context context) {
    15. if (mInstance == null) {
    16. synchronized (ConnectWifiUtils.class) {
    17. if (mInstance == null) {
    18. mInstance = new ConnectWifiUtils(context);
    19. }
    20. }
    21. }
    22. return mInstance;
    23. }
    24. public void setWifiConnectCallback(WifiConnectCallback wifiConnectCallback) {
    25. this.wifiConnectCallback = wifiConnectCallback;
    26. }
    27. /**
    28. * 连接Wifi
    29. *
    30. * @param scanResult 扫描结果
    31. * @param password 密码
    32. */
    33. public void connectWifi(WifiBean scanResult, String password) {
    34. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
    35. connectBySug(scanResult.getWifiName(), password);
    36. } else {
    37. connectByOld(scanResult, password);
    38. }
    39. }
    40. /**
    41. * Android 10 以下使用
    42. *
    43. * @param scanResult 扫描结果
    44. * @param password 密码
    45. */
    46. private void connectByOld(WifiBean scanResult, String password) {
    47. String ssid = scanResult.getWifiName();
    48. boolean isSuccess;
    49. WifiConfiguration configured = isExist(ssid);
    50. if (configured != null) {
    51. //在配置表中找到了,直接连接
    52. isSuccess = wifiManager.enableNetwork(configured.networkId, true);
    53. } else {
    54. WifiConfiguration wifiConfig = createWifiConfig(ssid, password, getCipherType(scanResult.getCapabilities()));
    55. int netId = wifiManager.addNetwork(wifiConfig);
    56. isSuccess = wifiManager.enableNetwork(netId, true);
    57. }
    58. Log.d(TAG, "connectWifi: " + (isSuccess ? "成功" : "失败"));
    59. }
    60. /**
    61. * Android 10及以上版本使用此方式连接Wifi
    62. *
    63. * @param ssid 名称
    64. * @param password 密码
    65. */
    66. @SuppressLint("NewApi")
    67. private void connectByNew(String ssid, String password) {
    68. WifiNetworkSpecifier wifiNetworkSpecifier = new WifiNetworkSpecifier.Builder()
    69. .setSsid(ssid)
    70. .setWpa2Passphrase(password)
    71. .build();
    72. //网络请求
    73. NetworkRequest request = new NetworkRequest.Builder()
    74. .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
    75. .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
    76. .addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
    77. .addCapability(NetworkCapabilities.NET_CAPABILITY_TRUSTED)
    78. .setNetworkSpecifier(wifiNetworkSpecifier)
    79. .build();
    80. //网络回调处理
    81. ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
    82. @Override
    83. public void onAvailable(@NonNull Network network) {
    84. super.onAvailable(network);
    85. if (wifiConnectCallback != null) {
    86. wifiConnectCallback.onSuccess(network);
    87. Log.d("WifiUtils", "======onAvailable: ====连接成功======");
    88. }
    89. }
    90. @Override
    91. public void onUnavailable() {
    92. super.onUnavailable();
    93. Log.d("WifiUtils", "======onAvailable: ====连接失败======");
    94. if (wifiConnectCallback != null) {
    95. wifiConnectCallback.onFailure();
    96. }
    97. }
    98. };
    99. //请求连接网络
    100. connectivityManager.requestNetwork(request, networkCallback);
    101. }
    102. @SuppressLint("NewApi")
    103. private void connectBySug(String ssid, String password) {
    104. WifiNetworkSuggestion suggestion = new WifiNetworkSuggestion.Builder()
    105. .setSsid(ssid)
    106. .setWpa2Passphrase(password)
    107. .setIsAppInteractionRequired(true)
    108. .build();
    109. List<WifiNetworkSuggestion> suggestionList = new ArrayList<>();
    110. suggestionList.add(suggestion);
    111. int status = wifiManager.addNetworkSuggestions(suggestionList);
    112. if (status != WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS) {
    113. return;
    114. }
    115. Log.d(TAG, "======onReceive: ==网络连接状态=111111111===");
    116. IntentFilter intentFilter = new IntentFilter(WifiManager.ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION);
    117. BroadcastReceiver wifiScanReceiver = new BroadcastReceiver() {
    118. @Override
    119. public void onReceive(Context context, Intent intent) {
    120. Log.d(TAG, "======onReceive: ==网络连接状态====");
    121. if (!intent.getAction().equals(WifiManager.ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION)) {
    122. return;
    123. }
    124. }
    125. };
    126. mContext.registerReceiver(wifiScanReceiver, intentFilter);
    127. }
    128. /**
    129. * 创建Wifi配置
    130. *
    131. * @param ssid 名称
    132. * @param password 密码
    133. * @param type 类型
    134. */
    135. private WifiConfiguration createWifiConfig(String ssid, String password, WifiCapability type) {
    136. WifiConfiguration config = new WifiConfiguration();
    137. config.allowedAuthAlgorithms.clear();
    138. config.allowedGroupCiphers.clear();
    139. config.allowedKeyManagement.clear();
    140. config.allowedPairwiseCiphers.clear();
    141. config.allowedProtocols.clear();
    142. config.SSID = "\"" + ssid + "\"";
    143. WifiConfiguration configured = isExist(ssid);
    144. if (configured != null) {
    145. wifiManager.removeNetwork(configured.networkId);
    146. wifiManager.saveConfiguration();
    147. }
    148. //不需要密码的场景
    149. if (type == WifiCapability.WIFI_CIPHER_NO_PASS) {
    150. config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    151. //以WEP加密的场景
    152. } else if (type == WifiCapability.WIFI_CIPHER_WEP) {
    153. config.hiddenSSID = true;
    154. config.wepKeys[0] = "\"" + password + "\"";
    155. config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
    156. config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
    157. config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    158. config.wepTxKeyIndex = 0;
    159. //以WPA加密的场景,自己测试时,发现热点以WPA2建立时,同样可以用这种配置连接
    160. } else if (type == WifiCapability.WIFI_CIPHER_WPA) {
    161. config.preSharedKey = "\"" + password + "\"";
    162. config.hiddenSSID = true;
    163. config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
    164. config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    165. config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
    166. config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
    167. config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    168. config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
    169. config.status = WifiConfiguration.Status.ENABLED;
    170. }
    171. return config;
    172. }
    173. /**
    174. * 网络是否连接
    175. */
    176. @SuppressLint("NewApi")
    177. public static boolean isNetConnected(ConnectivityManager connectivityManager) {
    178. return connectivityManager.getActiveNetwork() != null;
    179. }
    180. /**
    181. * 连接网络类型是否为Wifi
    182. */
    183. @SuppressLint("NewApi")
    184. public static boolean isWifi(ConnectivityManager connectivityManager) {
    185. if (connectivityManager.getActiveNetwork() == null) {
    186. return false;
    187. }
    188. NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(connectivityManager.getActiveNetwork());
    189. if (networkCapabilities != null) {
    190. return false;
    191. }
    192. return networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI);
    193. }
    194. /**
    195. * 配置表是否存在对应的Wifi配置
    196. *
    197. * @param SSID
    198. * @return
    199. */
    200. @SuppressLint("MissingPermission")
    201. private WifiConfiguration isExist(String SSID) {
    202. List<WifiConfiguration> existingConfigs = wifiManager.getConfiguredNetworks();
    203. for (WifiConfiguration existingConfig : existingConfigs) {
    204. if (existingConfig.SSID.equals("\"" + SSID + "\"")) {
    205. return existingConfig;
    206. }
    207. }
    208. return null;
    209. }
    210. private WifiCapability getCipherType(String capabilities) {
    211. if (capabilities.contains("WEB")) {
    212. return WifiCapability.WIFI_CIPHER_WEP;
    213. } else if (capabilities.contains("PSK")) {
    214. return WifiCapability.WIFI_CIPHER_WPA;
    215. } else if (capabilities.contains("WPS")) {
    216. return WifiCapability.WIFI_CIPHER_NO_PASS;
    217. } else {
    218. return WifiCapability.WIFI_CIPHER_NO_PASS;
    219. }
    220. }
    221. /**
    222. * wifi连接回调接口
    223. */
    224. public interface WifiConnectCallback {
    225. void onSuccess(Network network);
    226. void onFailure();
    227. }
    228. public enum WifiCapability {
    229. WIFI_CIPHER_WEP, WIFI_CIPHER_WPA, WIFI_CIPHER_NO_PASS
    230. }
    231. }

  • 相关阅读:
    grafana可视化
    视口标签viewport
    Android 5.1 open data flow 数据开启流程
    牛客SQL刷题第三趴——SQL大厂面试真题
    Tomcat请求处理流程与源码浅析
    《web课程设计》 基于HTML+CSS+JavaScript实现中国水墨风的小学学校网站模板(6个网页)
    C++ 学习宝藏网站分享
    流量再利用!佳信客服准备的企微拉新复购攻略来袭!
    分布式 - 服务器Nginx:基础系列之Nginx静态资源配置优化sendfile | tcp_nopush | tcp_nodelay
    ClickHouse UDF 官方示例Example报错解决方案
  • 原文地址:https://blog.csdn.net/shi450561200/article/details/133844050