如何监听连接到android热点的设备

时间:2015-03-25 07:05:21

标签: android android-wifi

这是我用来在android中创建热点的代码现在我想检测连接到它的设备的IP

// toggle wifi hotspot on or off
public static boolean configApState(Context context) {

    WifiManager wifimanager = (WifiManager) context.getSystemService(context.WIFI_SERVICE);
    WifiConfiguration wificonfiguration = null;
    try {  

        // if WiFi is on, turn it off
        if(isApOn(context)) {               
            wifimanager.setWifiEnabled(false);
        }               
        Method method = wifimanager.getClass().getMethod("setWifiApEnabled",  WifiConfiguration.class, boolean.class);                   
        method.invoke(wifimanager, wificonfiguration, !isApOn(context));
        return true;
    } 
    catch (Exception e) {

        e.printStackTrace();
    }       
    return false;
}

1 个答案:

答案 0 :(得分:2)

您可以使用以下代码获取连接的设备:

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(500);  // this is network call so we cant do that on UI thread, so i take background thread.
                    if (isReachable) {
                        Log.d("Device Information", ipAddress + " : "
                                + macAddress);
                    }

                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
});
thread.start();
}

来源:link