java wifi连接
时间: 2023-12-05 21:41:39 浏览: 55
以下是Java中连接WiFi的示例代码:
```java
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.content.Context;
public class WifiUtil {
private WifiManager wifiManager;
public WifiUtil(Context context) {
wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
}
// 连接WiFi
public void connectToWifi(String ssid, String password) {
WifiConfiguration wifiConfig = new WifiConfiguration();
wifiConfig.SSID = String.format("\"%s\"", ssid);
wifiConfig.preSharedKey = String.format("\"%s\"", password);
int netId = wifiManager.addNetwork(wifiConfig);
wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();
}
// 获取当前连接的WiFi信息
public String getCurrentWifiInfo() {
WifiInfo currentWifiInfo = wifiManager.getConnectionInfo();
return currentWifiInfo.toString();
}
// 将int类型的IP地址转换为String类型
public String intToIp(int ipAddress) {
return ((ipAddress & 0xff) + "." + (ipAddress >> 8 & 0xff) + "." + (ipAddress >> 16 & 0xff) + "." + (ipAddress >> 24 & 0xff));
}
}
```
其中,connectToWifi()方法用于连接WiFi,getCurrentWifiInfo()方法用于获取当前连接的WiFi信息,intToIp()方法用于将int类型的IP地址转换为String类型。
阅读全文