2017-09-13 93 views
2

嗯,我有一个情况,当我的手机作为热点工作,我需要检测连接到我的手机,并找到他们的MAC地址的所有设备。我写的是这样的:isReachable()返回false在android

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);回报只有当设备连接或断开假。我无法找到任何信息来寻找解决方案。还是有其他解决方案吗? (对于没有固定的电话)。

回答

0

嗯,我发现android保持MAC地址约10分钟(在不同的设备 - 不同的时间)addreses,并且唯一的方法 - 使用ADB shell命令来清除该列表,但!它仅适用于根植设备。

但这段代码可以帮助你(的作品不能与所有设备):

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(); 
}