以下是网络建议连接方式,希望有帮助:
const MainActivity = plus.android.runtimeMainActivity()
const wifiManager = MainActivity.getSystemService(Context.WIFI_SERVICE)
const ssid = wifi.SSID; // 要连接的 WiFi 的 SSID
const password = wifi.pwd; // WiFi 的密码
const Build = plus.android.importClass('android.os.Build');
const WifiNetworkSuggestion = plus.android.importClass('android.net.wifi.WifiNetworkSuggestion');
const ArrayList = plus.android.importClass('java.util.ArrayList');
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
const wifiNetworkSuggestion = new WifiNetworkSuggestion.Builder()
.setPriority(1)
.setSsid(ssid)
.setWpa2Passphrase(password)
.build();
const WifiNetworkSuggestionList = wifiManager.getNetworkSuggestions();
wifiManager.removeNetworkSuggestions(WifiNetworkSuggestionList);
const arrayList = new ArrayList();
arrayList.add(wifiNetworkSuggestion);
wifiManager.addNetworkSuggestions(arrayList);
}
还有一种方式是给当前app连接一个独享的wifi连接,代码如下(uts文件代码):
import Context from 'android.content.Context';
import WifiNetworkSpecifier from 'android.net.wifi.WifiNetworkSpecifier';
import NetworkRequest from 'android.net.NetworkRequest';
import NetworkCapabilities from 'android.net.NetworkCapabilities';
import ConnectivityManager from "android.net.ConnectivityManager";
import Network from "android.net.Network"
import NetworkCallback from "android.net.ConnectivityManager.NetworkCallback";
import MacAddress from "android.net.MacAddress"
/ 引入 interface.uts 文件中定义的变量 /
import { MyApiOptions, MyApiResult, MyApi, MyApiSync } from '../interface.uts';
/ 引入 unierror.uts 文件中定义的变量 /
import { MyApiFailImpl } from '../unierror';
export function connectWifi2(bssid : string, ssid : string, password : string) {
const connectivityManager = UTSAndroid.getAppContext()!.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager;
const wifiNetworkSpecifier = new WifiNetworkSpecifier.Builder()
.setBssid(MacAddress.fromString(bssid))
.setSsid(ssid)
.setWpa2Passphrase(password)
.build();
//网络请求
const request = new NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
.addCapability(NetworkCapabilities.NET_CAPABILITY_TRUSTED)
.setNetworkSpecifier(wifiNetworkSpecifier)
.build();
//网络回调处理
const networkCallback = new MyNetworkCallback();
//请求连接网络
connectivityManager.requestNetwork(request, networkCallback);
}
class MyNetworkCallback extends NetworkCallback {
constructor() {
super();
}
override onAvailable(network : Network) : void {
super.onAvailable(network);
console.log("======onAvailable: ====连接成功======");
}
override onUnavailable() : void {
super.onUnavailable();
console.log("======onAvailable: ====连接失败======");
}
}
Allan_Zhang
可以规避,compileSdkVersion使用28,不用Android9
2020-10-13 16:20