gpt4 book ai didi

java - isReachable() 在 android 中返回 false

转载 作者:行者123 更新时间:2023-11-29 02:37:31 36 4
gpt4 key购买 nike

好吧,当我的手机作为热点工作时,我需要检测所有连接到我手机的设备并找到它们的 MAC 地址。我写了这样的东西:

public void getListOfConnectedDevice() {
Thread thread = new Thread(new Runnable() {

@Override
public void run() {
BufferedReader br = null;
boolean isFirstLine = true;

try {
br = new BufferedReader(new FileReader("/proc/net/arp"));
String line;

while ((line = br.readLine()) != null) {
if (isFirstLine) {
isFirstLine = false;
continue;
}

String[] splitted = line.split(" +");

if (splitted != null && splitted.length >= 4) {

String ipAddress = splitted[0];
String macAddress = splitted[3];

boolean isReachable = InetAddress.getByName(
splitted[0]).isReachable(300);// this is network call so we cant do that on UI thread, so i take background thread.
Log.d(TAG, "ip: " + splitted[0]);
Log.d(TAG, "isReachable: " + isReachable);
if (isReachable) {
Log.d("Device Information", ipAddress + " : "
+ macAddress);
macAddresses.add(macAddress); //My List<String>
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
thread.start();
}

但是 boolean isReachable = InetAddress.getByName(
splitted[0]).isReachable(300);
仅在设备连接或断开时返回 false。而且我找不到任何信息来找到解决方案。或者还有其他解决方案吗? (对于没有根电话)。

最佳答案

好吧,我发现 android 将设备的 MAC 地址保留大约 10 分钟(在不同的设备上 - 不同的时间),并且唯一的方法 - 使用 ADB shell 命令清除该列表,但是!它仅适用于 Root设备。

但此代码可以帮助您(并非适用于所有设备):

public void getListOfConnectedDevice() {
final Thread thread = new Thread(new Runnable() {

@Override
public void run() {
macAddresses.clear();
BufferedReader br = null;
boolean isFirstLine = true;
try {

br = new BufferedReader(new FileReader("/proc/net/arp"));
String line;

while ((line = br.readLine()) != null) {
if (isFirstLine) {
isFirstLine = false;
continue;
}

String[] splitted = line.split(" +");

if (splitted != null && splitted.length >= 4) {

String ipAddress = splitted[0];
String macAddress = splitted[3];

Node node = new Node(ipAddress, macAddress);
boolean isReachable = node.isReachable;
Log.d(TAG, "isReachable: " + isReachable);
if (isReachable) {
Log.d("Device Information", ipAddress + " : "
+ macAddress);
macAddresses.add(macAddress);
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
thread.start();
}

关于java - isReachable() 在 android 中返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46207047/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com