下面給大家介紹Android 得到連接熱點的ip的方法 ,具體代碼如下所示:
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地址
private String intToIp(int paramInt) {return (paramInt & 0xFF) + "." + (0xFF & paramInt >> 8) + "." + (0xFF & paramInt >> 16) + "."+ (0xFF & paramInt >> 24);}當在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; } //輸出鏈接到當前設備的IP地址 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
總結
以上所述是小編給大家介紹的Android 得到連接熱點的ip的方法 ,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對VEVB武林網網站的支持!
新聞熱點
疑難解答