android 10 设置连接wifi 的方法代码
时间: 2023-12-17 11:04:46 浏览: 171
以下是在Android 10上连接WiFi的示例代码:
```java
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiNetworkSpecifier specifier = new WifiNetworkSpecifier.Builder()
.setSsid("Your WiFi SSID")
.setWpa2Passphrase("Your WiFi Password")
.build();
NetworkRequest request = new NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.setNetworkSpecifier(specifier)
.build();
ConnectivityManager connectivityManager = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
connectivityManager.requestNetwork(request, new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(@NonNull Network network) {
super.onAvailable(network);
// WiFi连接成功
}
@Override
public void onUnavailable() {
super.onUnavailable();
// WiFi连接失败
}
});
```
请注意,这段代码需要您的应用程序具有“android.permission.ACCESS_FINE_LOCATION”权限,因为Android 10需要这个权限才能在应用程序中连接WiFi。
阅读全文