Android获取连接到手机热点上的设备信息

主题:在手机开启热点网络的情况下,想要获取是哪个设备已经连接上了当前开启的热点。

实现思路:Android通过读取  /proc/net/arp 文件可以得到连接当前热点的设备信息,包括Mac地址、IP地址等信息。

一. 方法逻辑:

    /*** 获取连接到手机热点上的设备信息* @return*/public List<HashMap> getConnectedApInfo() {List<HashMap> connectedApInfo = new ArrayList<>();try {BufferedReader br = new BufferedReader(new FileReader("/proc/net/arp"));String line;while ((line = br.readLine()) != null) {/*** 获取到的数组结果,示例:[192.168.227.138, 0x1, 0x2, 82:64:5e:01:49:fc, *, wlan2]*/String[] splitted = line.split(" +");HashMap hashMap = new HashMap();//设备信息判断标准if (splitted.length >= 4 && splitted[3].contains(":")) {String ip = splitted[0];          //获取IP地址信息,代替设备名称String address = splitted[3];     //获取Mac地址信息hashMap.put("name", ip);hashMap.put("address", address);connectedApInfo.add(hashMap);Log.d(TAG, "getConnectedApInfo(),获取连接到手机热点上的设备信息:" + Arrays.toString(splitted) + "    connectedApInfo:" + connectedApInfo.size() + "  " + connectedApInfo);}}} catch (Exception e) {e.printStackTrace();}return connectedApInfo;}
二. 拓展工具类,控制热点的开启和关闭,热点信息的获取:
import static android.content.Context.CONNECTIVITY_SERVICE;
import java.io.BufferedReader;
import java.io.FileReader;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.ConnectivityManager;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.util.Log;
import com.android.dx.stock.ProxyBuilder;/*** Description:控制热点的开启和关闭,热点信息的获取* 所需权限:* <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />* <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />* <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />* <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />* <uses-permission android:name="android.permission.WRITE_SETTINGS"*     tools:ignore="ProtectedPermissions" /> <!-- 用于Android 6.0 (API 级别 23) 及以上版本 -->*/
public class WifiHotspotManager {private static final String TAG = WifiHotspotManager.class.getSimpleName();private WifiManager wifiManager;private Method method;public WifiHotspotManager(Context context) {wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);}public boolean isApEnabled() {try {if (method == null) {method = wifiManager.getClass().getMethod("isWifiApEnabled");}return (boolean) method.invoke(wifiManager);} catch (Exception e) {Log.e(TAG, "Error checking if AP is enabled", e);return false;}}/*** 开启或关闭热点* @param enabled* @return*/public boolean setApEnabled(boolean enabled) {if (enabled) {Log.d(TAG, "开启热点,Enabling hotspot");} else {Log.d(TAG, "关闭热点,Disabling hotspot");}try {if (method == null) {method = wifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);}return (boolean) method.invoke(wifiManager, null, enabled);} catch (Exception e) {Log.e(TAG, "开启或关闭热点 is error,enabling/disabling AP:" + e);return false;}}/*** 配置热点的设置(如SSID和密码)* 需要创建一个WifiConfiguration对象来配置你的热点设置,然后将其传递给configureApState方法* @param apConfig* @return*/public boolean configureApState(WifiConfiguration apConfig) {try {Method method = wifiManager.getClass().getMethod("setWifiApConfiguration", WifiConfiguration.class);return (boolean) method.invoke(wifiManager, apConfig);} catch (Exception e) {Log.e(TAG, "Error setting AP configuration", e);return false;}}/*** 控制热点的开启和关闭(一步到位)*/public boolean controlApSwitch(Context context, boolean flag){WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);try{WifiConfiguration apConfig = new WifiConfiguration();String deviceModel = Build.MODEL;     //设备型号apConfig.SSID = deviceModel;          //配置热点的名称apConfig.preSharedKey = "12345678";   //配置热点的密码(至少8位)apConfig.allowedKeyManagement.set(4); //配置密码加密方式//通过反射调用设置热点Method method = wifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, Boolean.TYPE);Boolean rs = (Boolean) method.invoke(wifiManager, apConfig, flag);        //true 开启热点 ,false 关闭热点Log.d(TAG, flag ? "当前设备:" + deviceModel + " 开启热点网络是否成功:" + rs : " 关闭热点网络是否成功:" + rs);return rs;} catch(Exception e){e.printStackTrace();return false;}}/*** 发送隐式广播。此方法会查询与给定意图相匹配的所有广播接收器,并向每个匹配的接收器发送一个显式广播。** @param context 上下文,用于发送广播。* @param intent 需要发送的隐式广播意图。* @param action 执行的动作*/public void sendImplicitBroadcast(Context context, Intent intent, String action) {// 获取包管理器,用于查询广播接收器PackageManager pm = context.getPackageManager();// 查询与intent相匹配的所有广播接收器List<ResolveInfo> matches = pm.queryBroadcastReceivers(intent, 0);// 遍历所有匹配的广播接收器for (ResolveInfo resolveInfo : matches) {// 创建一个新的意图,将其转换为显式意图,目标为当前接收器Intent explicit = new Intent(intent);// 设置组件名称,转换为显式意图ComponentName cn = new ComponentName(resolveInfo.activityInfo.applicationInfo.packageName, resolveInfo.activityInfo.name);explicit.setComponent(cn);// 向每个匹配的广播接收器发送显式广播context.sendBroadcast(explicit);}Log.d(TAG, "sendImplicitBroadcast(),发送隐式广播,action:" + action);}/*** 打开手机的热点* 需要在build.gradle文件添加三方库依赖:implementation 'com.linkedin.dexmaker:dexmaker-mockito:2.12.1'* @param context*/public void startTethering(Context context){ConnectivityManager connectivityManager = ((ConnectivityManager)context.getSystemService(CONNECTIVITY_SERVICE));try{Class classOnStartTetheringCallback = Class.forName("android.net.ConnectivityManager$OnStartTetheringCallback");Method startTethering=connectivityManager.getClass().getDeclaredMethod("startTethering",int.class,boolean.class,classOnStartTetheringCallback);Object proxy = ProxyBuilder.forClass(classOnStartTetheringCallback).handler(new InvocationHandler(){@Overridepublic Object invoke(Object o,Method method,Object[]objects)throws Throwable{return null;}}).build();startTethering.invoke(connectivityManager,0,false,proxy);} catch(Exception e){e.printStackTrace();}Log.d(TAG, "startTethering(),打开手机的热点");}/*** 关闭手机的热点*/public void stopTethering(Context context){ConnectivityManager connectivityManager=((ConnectivityManager)context.getSystemService(CONNECTIVITY_SERVICE));try{Method stopTethering = connectivityManager.getClass().getDeclaredMethod("stopTethering",int.class);stopTethering.invoke(connectivityManager,0);}catch(Exception e){e.printStackTrace();}Log.d(TAG, "stopTethering(),关闭手机的热点");}/*** 判断是否开启手机的热点* @param context* @return*/public boolean isWifiApEnabled(Context context){WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);try{Method method=wifiManager.getClass().getMethod("isWifiApEnabled");method.setAccessible(true);return(Boolean)method.invoke(wifiManager);}catch(NoSuchMethodException e){e.printStackTrace();}catch(Exception e){e.printStackTrace();}Log.d(TAG, "isWifiApEnabled(),判断是否开启手机的热点");return false;}/*** 获取手机的热点信息* @param context* @return*/public String getApInfo(Context context){WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);try{Method localMethod = wifiManager.getClass().getDeclaredMethod("getWifiApConfiguration", new Class[0]);Object config = localMethod.invoke(wifiManager);Log.d(TAG, "getApInfo(),获取手机的热点信息:" + config.toString());}catch(Exception localException){localException.printStackTrace();}return null;}/*** 获取连接到手机热点上的设备信息* @return*/public List<HashMap> getConnectedApInfo() {List<HashMap> connectedApInfo = new ArrayList<>();try {BufferedReader br = new BufferedReader(new FileReader("/proc/net/arp"));String line;while ((line = br.readLine()) != null) {/*** 获取到的数组结果,示例:[192.168.227.138, 0x1, 0x2, 82:64:5e:01:49:fc, *, wlan2]*/String[] splitted = line.split(" +");HashMap hashMap = new HashMap();//设备信息判断标准if (splitted.length >= 4 && splitted[3].contains(":")) {String ip = splitted[0];          //获取IP地址信息,代替设备名称String address = splitted[3];     //获取Mac地址信息hashMap.put("name", ip);hashMap.put("address", address);connectedApInfo.add(hashMap);Log.d(TAG, "getConnectedApInfo(),获取连接到手机热点上的设备信息:" + Arrays.toString(splitted) + "    connectedApInfo:" + connectedApInfo.size() + "  " + connectedApInfo);}}} catch (Exception e) {e.printStackTrace();}return connectedApInfo;}
三. 调用示例:
//返回的是一个数据形式是包含HahMap集合的List集合,可根据HashMap的键值对取值并显示
WifiHotspotManager wifiHotspotManager = new WifiHotspotManager(requireActivity());List<HashMap> connectedApInfo = wifiHotspotManager.getConnectedApInfo();Log.d(TAG, "connectedApInfo:" + connectedApInfo.size() + "  " + connectedApInfo);
四.手机热点已连接设备与功能效果图

参考文章:Android获取实时连接热点的设备IP_安卓设备获取ip-CSDN博客

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

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

相关文章

Hadoop安装部署-NameNode高可用版

Hadoop分布式文件系统支持NameNode的高可用性&#xff0c;本文主要描述NameNode多节点高可用性的安装部署。 如上所示&#xff0c;Hadoop分布式文件系统部署了NameNode的Master主节点以及NameNode的Slave副节点&#xff0c;当Master主节点发生故障变得不可用时&#xff0c;ZooK…

【C语言】扫雷小游戏

文章目录 前言一、游戏玩法二、创建文件test.c文件menu()——打印菜单game()——调用功能函数&#xff0c;游戏的实现main()主函数 game.c文件初始化棋盘打印棋盘随机布置雷的位置统计周围雷的个数展开周围一片没有雷的区域计算已排查位置的个数排查雷(包括检测输赢): game.h文…

3d模型太大怎么把物体显示小---模大狮模型网

在3D建模软件中&#xff0c;您可以通过缩放操作来改变物体的大小以便于显示和编辑。以下是在常见的3D建模软件(例如Blender、Maya、3ds Max等)中缩小物体的方法&#xff1a; Blender中缩小物体&#xff1a; 选择物体&#xff1a;首先&#xff0c;选择您想要缩小的物体。您可以…

科研学习|科研软件——SPSS统计作图教程:多组折线图(≥3个变量)

一、问题与数据 研究者想研究45-65岁不同性别人群中静坐时长和血胆固醇水平的关系,分别招募50名男性和女性(gender)询问其每天静坐时长(time,分钟),并检测其血液中胆固醇水平(cholesterol, mmol/L),部分数据如图1。研究者该如何绘图展示这两者间的关系呢? 二、问题…

秋招复习笔记——八股文部分:操作系统

笔试得刷算法题&#xff0c;那面试就离不开八股文&#xff0c;所以特地对着小林coding的图解八股文系列记一下笔记。 这一篇笔记是图解系统的内容。 硬件结构 CPU执行程序 计算机基本结构为 5 个部分&#xff0c;分别是运算器、控制器、存储器、输入设备、输出设备&#xf…

进制转换(0123456789ABCDEF)

题目 import java.util.Scanner;public class Main {public static void main(String[] args) {//将十进制数M转化为N进制数Scanner sc new Scanner(System.in);int m sc.nextInt();int n sc.nextInt();StringBuffer sb new StringBuffer();//1String s "0123456789…

坚持十天做完Python入门100题第一天

坚持十天做完Python入门100题第一天 第1题 变量更新第2题 变量命名规则第3题 类型错误第4题 序列索引第5题 序列切片第6题 负数切片第7题 Range函数 第1题 变量更新 解析&#xff1a;Python代码的读取和执行是由上至下的&#xff0c;变量n一开始被赋值为1&#xff0c;但被更新了…

每日OJ题_两个数组dp⑤_力扣10. 正则表达式匹配

目录 力扣10. 正则表达式匹配 解析代码 力扣10. 正则表达式匹配 10. 正则表达式匹配 难度 困难 给你一个字符串 s 和一个字符规律 p&#xff0c;请你来实现一个支持 . 和 * 的正则表达式匹配。 . 匹配任意单个字符* 匹配零个或多个前面的那一个元素 所谓匹配&#xff0c…

项目管理-Jiar Software

文章目录 前言Jira 中的关键词或术语功能应用场景优势 总结 前言 Jira Software 是由澳大利亚公司 Atlassian 开发的一款领先的敏捷项目管理工具&#xff0c;广泛应用于软件开发团队&#xff0c;以支持复杂的项目管理需求。以下是关于 Jira Software 的详细介绍&#xff0c;包…

安全左移是什么,如何为网络安全建设及运营带来更多可能性

长久以来&#xff0c;网络安全技术产品和市场需求都聚焦于在“右侧”防护&#xff0c;即在各种系统、业务已经投入使用的网络环境外围或边界&#xff0c;检测进出的流量、行为等是不是存在风险&#xff0c;并对其进行管控或调整。 然而事实上&#xff0c;安全风险不仅是“跑”…

Harmony鸿蒙南向驱动开发-GPIO

GPIO&#xff08;General-purpose input/output&#xff09;即通用型输入输出。通常&#xff0c;GPIO控制器通过分组的方式管理所有GPIO管脚&#xff0c;每组GPIO有一个或多个寄存器与之关联&#xff0c;通过读写寄存器完成对GPIO管脚的操作。 基本概念 GPIO又俗称为I/O口&am…

YOLOV8主干改进方法:DenseNet——最新提出DenseOne密集网络,打造高性能检测器(附改进代码)

原论文地址:原论文下载地址 优点:使得网络更容易训练,参数更小且计算更高效 摘要:最近的研究表明,如果卷积网络在靠近输入和接近输出的层之间包含更短的连接,那么卷积网络可以更深入、更准确、更有效地训练。在本文中,我们接受了这一观察结果,并引入了密集卷积网络(De…