WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
if (!wifiManager.isWifiEnabled()) {
System.out.println("=================");
wifiManager.setWifiEnabled(true);
}
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String IPAddress = intToIp(wifiInfo.getIpAddress());
System.out.println("IPAddress-->>" + IPAddress);
DhcpInfo dhcpinfo = wifiManager.getDhcpInfo();
String serverAddress = intToIp(dhcpinfo.serverAddress);
System.out.println("serverAddress-->>" + serverAddress);
其中IPAddress 是本机的IP地址,serverAddress 是你所连接的wifi热点对应的IP地址
当在Android设备终端上使用Wifi热点的时候,需要获知Wifi热点的运行状态,热点是否打开,连接到该WIFI热点的设备数量,以及连接设备的具体IP和MAC地址。
使用re文件管理器去"/proc/net/arp",打开,发现连接上热点的设备信息都在这里了,包括mac ip等。
鉴于此,我们可以在代码中打开该文件,并获取WIFI热点的信息。
获取WIFI热点状态的方法getWifiApState()和判断热点是否可用的方法isApEnabled(),在Android源码WifiManager.Java中已经实现,但是它们是Hide方法,在SDK层面是不能访问的,如要访问需要用到java反射的机制。具体代码实现如下:
其中定义WIFI AP的几个状态
- public static final int WIFI_AP_STATE_DISABLING = 10;
- public static final int WIFI_AP_STATE_DISABLED = 11;
- public static final int WIFI_AP_STATE_ENABLING = 12;
- public static final int WIFI_AP_STATE_ENABLED = 13;
- public static final int WIFI_AP_STATE_FAILED = 14;
对应于WifiMangaer.java中对这几个状态的定义。
获取WIFI热点的状态:
- public int getWifiApState(Context mContext) {
- WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
- try {
- Method method = wifiManager.getClass().getMethod("getWifiApState");
- int i = (Integer) method.invoke(wifiManager);
- Log.i(TAG,"wifi state: " + i);
- return i;
- } catch (Exception e) {
- Log.e(TAG,"Cannot get WiFi AP state" + e);
- return WIFI_AP_STATE_FAILED;
- }
- }
判断Wifi热点是否可用:
- public boolean isApEnabled(Context mContext) {
- int state = getWifiApState(mContext);
- return WIFI_AP_STATE_ENABLING == state || WIFI_AP_STATE_ENABLED == state;
- }
获取链接到当前热点的设备IP:
- private ArrayList<String> getConnectedHotIP() {
- ArrayList<String> connectedIP = new ArrayList<String>();
- try {
- BufferedReader br = new BufferedReader(new FileReader(
- "/proc/net/arp"));
- String line;
- while ((line = br.readLine()) != null) {
- String[] splitted = line.split(" +");
- if (splitted != null && splitted.length >= 4) {
- String ip = splitted[0];
- connectedIP.add(ip);
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return connectedIP;
- }
- public void printHotIp() {
-
- ArrayList<String> connectedIP = getConnectedHotIP();
- StringBuilder resultList = new StringBuilder();
- for (String ip : connectedIP) {
- resultList.append(ip);
- resultList.append("\n");
- }
- System.out.print(resultList);
- Log.d(TAG,"---->>heww resultList="+resultList);
- }
当然在应用中要添加访问WIFI设备的权限:
- <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
否则将会提示如下错误:
Cannot get WiFi AP state