2017-09-13 119 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(); 
}