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

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

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

Android 10以上则可以使用

  WifiNetworkSpecifier wifiNetworkSpecifier = new WifiNetworkSpecifier.Builder().setSsid(ssid).setWpa2Passphrase(password).build();//网络请求NetworkRequest request = new NetworkRequest.Builder().addTransportType(NetworkCapabilities.TRANSPORT_WIFI).removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED).addCapability(NetworkCapabilities.NET_CAPABILITY_TRUSTED).setNetworkSpecifier(wifiNetworkSpecifier).build();//网络回调处理ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {@Overridepublic void onAvailable(@NonNull Network network) {super.onAvailable(network);if (wifiConnectCallback != null) {wifiConnectCallback.onSuccess(network);Log.d("WifiUtils", "======onAvailable: ====连接成功======");}}@Overridepublic void onUnavailable() {super.onUnavailable();Log.d("WifiUtils", "======onAvailable: ====连接失败======");if (wifiConnectCallback != null) {wifiConnectCallback.onFailure();}}};//连接网络connectivityManager.requestNetwork(request, networkCallback);

或是WifiNetworkSuggestion 方式

 WifiNetworkSuggestion suggestion = new WifiNetworkSuggestion.Builder().setSsid(ssid).setWpa2Passphrase(password).setIsAppInteractionRequired(true).build();

最后分享工具类

public class ConnectWifiUtils {private static final String TAG = ConnectWifiUtils.class.getSimpleName();private final ConnectivityManager connectivityManager;//连接管理者private final WifiManager wifiManager;//Wifi管理者private WifiConnectCallback wifiConnectCallback;@SuppressLint("StaticFieldLeak")private static volatile ConnectWifiUtils mInstance;private final Context mContext;public ConnectWifiUtils(Context context) {mContext = context;wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);}public static ConnectWifiUtils initialize(Context context) {if (mInstance == null) {synchronized (ConnectWifiUtils.class) {if (mInstance == null) {mInstance = new ConnectWifiUtils(context);}}}return mInstance;}public void setWifiConnectCallback(WifiConnectCallback wifiConnectCallback) {this.wifiConnectCallback = wifiConnectCallback;}/*** 连接Wifi** @param scanResult 扫描结果* @param password   密码*/public void connectWifi(WifiBean scanResult, String password) {if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {connectBySug(scanResult.getWifiName(), password);} else {connectByOld(scanResult, password);}}/*** Android 10 以下使用** @param scanResult 扫描结果* @param password   密码*/private void connectByOld(WifiBean scanResult, String password) {String ssid = scanResult.getWifiName();boolean isSuccess;WifiConfiguration configured = isExist(ssid);if (configured != null) {//在配置表中找到了,直接连接isSuccess = wifiManager.enableNetwork(configured.networkId, true);} else {WifiConfiguration wifiConfig = createWifiConfig(ssid, password, getCipherType(scanResult.getCapabilities()));int netId = wifiManager.addNetwork(wifiConfig);isSuccess = wifiManager.enableNetwork(netId, true);}Log.d(TAG, "connectWifi: " + (isSuccess ? "成功" : "失败"));}/*** Android 10及以上版本使用此方式连接Wifi** @param ssid     名称* @param password 密码*/@SuppressLint("NewApi")private void connectByNew(String ssid, String password) {WifiNetworkSpecifier wifiNetworkSpecifier = new WifiNetworkSpecifier.Builder().setSsid(ssid).setWpa2Passphrase(password).build();//网络请求NetworkRequest request = new NetworkRequest.Builder().addTransportType(NetworkCapabilities.TRANSPORT_WIFI).removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED).addCapability(NetworkCapabilities.NET_CAPABILITY_TRUSTED).setNetworkSpecifier(wifiNetworkSpecifier).build();//网络回调处理ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {@Overridepublic void onAvailable(@NonNull Network network) {super.onAvailable(network);if (wifiConnectCallback != null) {wifiConnectCallback.onSuccess(network);Log.d("WifiUtils", "======onAvailable: ====连接成功======");}}@Overridepublic void onUnavailable() {super.onUnavailable();Log.d("WifiUtils", "======onAvailable: ====连接失败======");if (wifiConnectCallback != null) {wifiConnectCallback.onFailure();}}};//请求连接网络connectivityManager.requestNetwork(request, networkCallback);}@SuppressLint("NewApi")private void connectBySug(String ssid, String password) {WifiNetworkSuggestion suggestion = new WifiNetworkSuggestion.Builder().setSsid(ssid).setWpa2Passphrase(password).setIsAppInteractionRequired(true).build();List<WifiNetworkSuggestion> suggestionList = new ArrayList<>();suggestionList.add(suggestion);int status = wifiManager.addNetworkSuggestions(suggestionList);if (status != WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS) {return;}Log.d(TAG, "======onReceive: ==网络连接状态=111111111===");IntentFilter intentFilter = new IntentFilter(WifiManager.ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION);BroadcastReceiver wifiScanReceiver = new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {Log.d(TAG, "======onReceive: ==网络连接状态====");if (!intent.getAction().equals(WifiManager.ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION)) {return;}}};mContext.registerReceiver(wifiScanReceiver, intentFilter);}/*** 创建Wifi配置** @param ssid     名称* @param password 密码* @param type     类型*/private WifiConfiguration createWifiConfig(String ssid, String password, WifiCapability type) {WifiConfiguration config = new WifiConfiguration();config.allowedAuthAlgorithms.clear();config.allowedGroupCiphers.clear();config.allowedKeyManagement.clear();config.allowedPairwiseCiphers.clear();config.allowedProtocols.clear();config.SSID = "\"" + ssid + "\"";WifiConfiguration configured = isExist(ssid);if (configured != null) {wifiManager.removeNetwork(configured.networkId);wifiManager.saveConfiguration();}//不需要密码的场景if (type == WifiCapability.WIFI_CIPHER_NO_PASS) {config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);//以WEP加密的场景} else if (type == WifiCapability.WIFI_CIPHER_WEP) {config.hiddenSSID = true;config.wepKeys[0] = "\"" + password + "\"";config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);config.wepTxKeyIndex = 0;//以WPA加密的场景,自己测试时,发现热点以WPA2建立时,同样可以用这种配置连接} else if (type == WifiCapability.WIFI_CIPHER_WPA) {config.preSharedKey = "\"" + password + "\"";config.hiddenSSID = true;config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);config.status = WifiConfiguration.Status.ENABLED;}return config;}/*** 网络是否连接*/@SuppressLint("NewApi")public static boolean isNetConnected(ConnectivityManager connectivityManager) {return connectivityManager.getActiveNetwork() != null;}/*** 连接网络类型是否为Wifi*/@SuppressLint("NewApi")public static boolean isWifi(ConnectivityManager connectivityManager) {if (connectivityManager.getActiveNetwork() == null) {return false;}NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(connectivityManager.getActiveNetwork());if (networkCapabilities != null) {return false;}return networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI);}/*** 配置表是否存在对应的Wifi配置** @param SSID* @return*/@SuppressLint("MissingPermission")private WifiConfiguration isExist(String SSID) {List<WifiConfiguration> existingConfigs = wifiManager.getConfiguredNetworks();for (WifiConfiguration existingConfig : existingConfigs) {if (existingConfig.SSID.equals("\"" + SSID + "\"")) {return existingConfig;}}return null;}private WifiCapability getCipherType(String capabilities) {if (capabilities.contains("WEB")) {return WifiCapability.WIFI_CIPHER_WEP;} else if (capabilities.contains("PSK")) {return WifiCapability.WIFI_CIPHER_WPA;} else if (capabilities.contains("WPS")) {return WifiCapability.WIFI_CIPHER_NO_PASS;} else {return WifiCapability.WIFI_CIPHER_NO_PASS;}}/*** wifi连接回调接口*/public interface WifiConnectCallback {void onSuccess(Network network);void onFailure();}public enum WifiCapability {WIFI_CIPHER_WEP, WIFI_CIPHER_WPA, WIFI_CIPHER_NO_PASS}}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/108632.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

System.exit()方法参数

说明文档&#xff1a;System (Java Platform SE 8 ) 终止当前正在运行的Java虚拟机。该参数用作状态代码&#xff1b;按照惯例&#xff0c;非零状态码表示异常终止。 此方法调用类Runtime中的exit方法。此方法从不正常返回。 调用System.exit&#xff08;n&#xff09;实际上等…

Android MediaCodec将h264实时视频流数据解码为yuv,并转换yuv的颜色格式为nv21

初始化mediacodec //宽高根据摄像头分辨率设置private int Width 1280;private int Height 720;private MediaCodec mediaCodec;private ByteBuffer[] inputBuffers;private void initMediaCodec(Surface surface) {try {Log.d(TAG, "onGetNetVideoData: ");//创建…

牛客:FZ12 牛牛的顺时针遍历

FZ12 牛牛的顺时针遍历 文章目录 FZ12 牛牛的顺时针遍历题目描述题解思路题解代码 题目描述 题解思路 通过一个变量来记录当前方向&#xff0c;遍历矩阵&#xff0c;每次遍历一条边&#xff0c;将该边的信息加入到结果中 题解代码 func spiralOrder(matrix [][]int) []int {…

MySQL中如何进行表的优化和压缩?

在MySQL中&#xff0c;可以通过以下方式进行表的优化和压缩&#xff1a; 使用合适的存储引擎&#xff08;Storage Engine&#xff09;&#xff1a;MySQL提供了多种存储引擎&#xff0c;如InnoDB、MyISAM等。不同的存储引擎在表的优化和压缩方面有不同的特点。例如&#xff0c;I…

Docker安装ES7.14和Kibana7.14(无账号密码)

一、Docker安装ES7.14.0 1、下载镜像 docker pull elasticsearch:7.14.0 2、docker安装7.14.0 mkdir -p /usr/local/elasticsearch/config mkdir -p /usr/local/elasticsearch/data chmod 777 -R /usr/local/elasticsearch/ echo "http.host: 0.0.0.0" >> /u…

IDEA中点击New没有Java Class

解决办法&#xff1a;右键src&#xff0c;也可以是其他文件名&#xff0c;点击Mark Directory as 点击Sources Root即可

【Java 进阶篇】JavaScript DOM Element 对象详解

JavaScript是一门广泛用于网页开发的脚本语言&#xff0c;而DOM&#xff08;文档对象模型&#xff09;是JavaScript在网页中操作HTML和XML文档的核心。DOM以树状结构表示文档&#xff0c;允许开发者以编程方式访问、操作和修改文档的内容和结构。在DOM中&#xff0c;Element对象…

海洋CMS仿爱美剧影视电影视频网站模版源码/自适应手机端

海洋CMS仿爱美剧网站模板&#xff0c;自适应手机端&#xff0c;内含视频、资讯、留言模块。 下载地址&#xff1a;https://bbs.csdn.net/topics/617419787

JUC并发编程——四大函数式接口(基于狂神说的学习笔记)

四大函数式接口 函数式接口&#xff1a;只有一个方法的接口 &#xff0c;例如&#xff1a;Runnable接口 Function 函数型接口&#xff0c;有一个输入参数&#xff0c;有一个输出 源码&#xff1a; /*** Represents a function that accepts one argument and produces a resul…

队栈

题目描述 Yazid 是一名 OI 初学者。他最近在研究基础数据结构:队列和栈。某天,Yazid 脑洞大开,发明了一种叫做“队栈”的数据结构。众所周知,队列是先进先出的数据结构,而栈是先进后出的数据结构。而 Yazid 发明的队栈则同时支持查询并删除其中 最早被插入的元素和最晚被插入的…

Postman简单使用

文章目录 一.接口测试流程二、Postman接口测试工具三、接口关联四、全局变量和环境变量 一.接口测试流程 拿到API接口文档&#xff08;从开发拿或者抓包获取&#xff09;&#xff0c;熟悉接口业务&#xff0c;接口地址&#xff0c;错误码等等 编写接口的测试用例以及评审 编写…

docker中使用GPU+rocksdb

配置环境 delldell-Precision-3630-Tower  ~  lsb_release -a No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 20.04.6 LTS Release: 20.04 Codename: focaldelldell-Precision-3630-Tower  ~  nvcc --version nvcc: NVIDIA (R) Cuda comp…

【数据结构】排序--快速排序

目录 一 概念 二 快速排序的实现 1. hoare版本 (1)代码实现 (2)单趟排序图解 (3) 递归实现图解 (4)细节控制 (5)时间复杂度 (6)三数取中优化 2 挖坑法 (1)代码实现 (2)单趟图解 3 前后指针法 (1) 代码实现 (2) 单趟图解 ​编辑4 优化子区间 5 非递归快速排…

FPGA project : flash_write

本实验重点学习了&#xff1a; flash的页编程指令pp。 在写之前要先进行擦除&#xff08;全擦除和页擦除&#xff09;&#xff1b; 本实验&#xff1a;先传写指令&#xff0c;然后进入写锁存周期&#xff0c;然后传页编程指令&#xff0c;3个地址&#xff1b; 然后传数据&a…

【Java基础面试十五】、 说一说你对多态的理解

文章底部有个人公众号&#xff1a;热爱技术的小郑。主要分享开发知识、学习资料、毕业设计指导等。有兴趣的可以关注一下。为何分享&#xff1f; 踩过的坑没必要让别人在再踩&#xff0c;自己复盘也能加深记忆。利己利人、所谓双赢。 面试官&#xff1a;说一说你对多态的理解 …

常见6种易被忽略的软件隐藏缺陷

软件隐藏缺陷常常会被测试人员忽略或遗漏&#xff0c;其往往会对项目的成功和用户体验产生不可忽视的负面影响&#xff0c;易造成软件数据泄露、系统崩溃或安全问题等&#xff0c;直接影响系统稳定性和用户满意度。 因此我们需要高度重视软件的隐藏缺陷&#xff0c;重视全面的软…

开源项目汇总

element-plus 人人开源 人人开源 多租户 若依 jeecg https://gitee.com/jeecg/jeecg?_fromgitee_search#https://gitee.com/link?targethttp%3A%2F%2Fidoc.jeecg.com jeeplus JeePlus快速开发平台 j2eefast Sa-Plus

“Flex弹性布局、轮播图mock遍历数据和首页布局解析与实践“

目录 引言1. Flex弹性布局介绍及使用什么是Flex弹性布局&#xff1f;Flex容器与Flex项目Flex属性详解 2. 轮播图mock遍历数据简述轮播图的作用和意义处理mock数据的重要性使用Mock模拟数据遍历 3. 首页布局总结 引言 在现代网页开发中&#xff0c;灵活性和响应式布局是至关重要…

Hadoop知识点+面试题大全

20道面试题及详细解答&#xff01; 1.说说什么是结构化数据、非结构化数据和半结构化数据 结构化数据、非结构化数据和半结构化数据是根据数据的组织结构和格式来划分的不同类型的数据。 结构化数据&#xff1a;结构化数据是按照预定义的数据模型进行组织和存储的数据。它通常…

linux 查看系统版本

命令&#xff1a;lsb_release -a 可能遇到的问题&#xff1a; 问题1&#xff1a; 报错&#xff1a;command not found: lsb_release原因&#xff1a;系统没有安装 lsb_release解决方案&#xff1a;sudo apt-get install lsb-release 问题2&#xff1a; 报错&#xff1a; Tra…