Android Obtains the code of Hotspot Host ip and Connect Hotspot Mobile Phone ip
- 2021-08-12 03:38:55
- OfStack
Which defines several states of WIFI and 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;
Corresponds to the definitions of these states in WifiMangaer. java.
Get the status of an WIFI hotspot:
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;
}
}
Determine whether Wifi hotspots are available:
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;
}
// Object linked to the current device IP Address
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);
}
Of course, you should add access to WIFI devices in your application:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
The code to get the ip address of the hotspot host:
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
DhcpInfo info=wifiManager.getDhcpInfo();
System.out.println(info.serverAddress);
Summarize