提交 00eace7e 编写于 作者: DCloud_iOS_XHY's avatar DCloud_iOS_XHY

Merge branch 'dev' of gitcode.net:dcloud/uni-api into dev

{"index":1}
\ No newline at end of file
......@@ -37,7 +37,7 @@
testConnnectWifi(){
uni.connectWifi({
partialInfo:false,
maunal:false,
SSID:"Xiaomi_20D0",
password:"BBBB",
complete:(res)=>{
......
import Context from "android.content.Context";
import BatteryManager from "android.os.BatteryManager";
import { getAppContext } from "io.dcloud.uts.android";
import { UTSAndroid } from "io.dcloud.uts";
type GetBatteryInfoOptions = {
......@@ -10,7 +10,7 @@ type GetBatteryInfoOptions = {
}
export default function getBatteryInfo(options: GetBatteryInfoOptions) {
const context = getAppContext();
const context = UTSAndroid.getAppContext();
if (context != null) {
const manager = context.getSystemService(
Context.BATTERY_SERVICE
......
......@@ -8,7 +8,7 @@
],
"repository": "",
"engines": {
"HBuilderX": "^3.6.8"
"HBuilderX": "^3.6.9"
},
"dcloudext": {
"type": "uts",
......
{
"minSdkVersion": "19"
}
\ No newline at end of file
import { onAppTrimMemory, offAppTrimMemory ,onAppActivityDestroy} from "io.dcloud.uts.android"
import { UTSAndroid } from "io.dcloud.uts"
let listeners: UTSCallback[] = []
......@@ -8,11 +8,13 @@ const onAppTrimMemoryListener = (res: number) => {
})
}
@Suppress("DEPRECATION")
export function onMemoryWarning(callback: (res: number) => void) {
if (listeners.length === 0) {
if (listeners.length == 0) {
// 仅首次执行底层的实际监听
onAppTrimMemory(onAppTrimMemoryListener)
onAppActivityDestroy(()=>{
UTSAndroid.onAppTrimMemory(onAppTrimMemoryListener)
UTSAndroid.onAppActivityDestroy(()=>{
// listeners 默认是静态常量周期,activity 销毁时,需要手动清空
listeners = []
})
......@@ -20,12 +22,13 @@ export function onMemoryWarning(callback: (res: number) => void) {
listeners.push(callback)
}
@Suppress("DEPRECATION")
export function offMemoryWarning(callback: UTSCallback | null = null) {
if(callback == null){
// 清除全部回调
listeners = []
offAppTrimMemory(null);
UTSAndroid.offAppTrimMemory(null);
return
}
......@@ -34,8 +37,8 @@ export function offMemoryWarning(callback: UTSCallback | null = null) {
if (index > -1) {
listeners.splice(index, 1)
}
if (listeners.length === 0) {
if (listeners.length == 0) {
// 当用户不再监听时,移除底层实际监听
offAppTrimMemory(onAppTrimMemoryListener)
UTSAndroid.offAppTrimMemory(onAppTrimMemoryListener)
}
}
import {
getUniActivity
} from "io.dcloud.uts.android";
UTSAndroid
} from "io.dcloud.uts";
import ActivityCompat from "androidx.core.app.ActivityCompat";
......@@ -35,7 +35,7 @@ let imageChange: UTSCallback | null = null;
/**
* android 文件监听实现
*/
@Suppress("DEPRECATION")
class ScreenFileObserver extends FileObserver {
/**
......@@ -85,12 +85,13 @@ class ScreenFileObserver extends FileObserver {
/**
* 开启截图监听
*/
@Suppress("DEPRECATION")
export function onUserCaptureScreen(callback: (res:UTSJSONObject) => void) {
// 检查相关权限是否已经具备
if (ActivityCompat.checkSelfPermission(getUniActivity()!, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.checkSelfPermission(UTSAndroid.getUniActivity()!, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
// 不具备权限,申请权限,并且告知用户监听失败
ActivityCompat.requestPermissions(getUniActivity()!, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1001)
ActivityCompat.requestPermissions(UTSAndroid.getUniActivity()!, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1001)
// 因权限缺失导致监听失败
let ret = {
......
# wa-wifi
### 开发文档
[UTS 语法](https://uniapp.dcloud.net.cn/tutorial/syntax-uts.html)
[UTS 原生插件](https://uniapp.dcloud.net.cn/plugin/uts-plugin.html)
[Hello UTS](https://gitcode.net/dcloud/hello-uts/-/tree/dev)
\ No newline at end of file
# uni-wifi
WiFi信息相关
### uni.getConnectedWifi
获取当前设备连接的WiFi信息。
> iOS使用此接口注意事项:
> 1.iOS使用此接口需要添加Access WiFi information的Capabilities, 此能力不需要开发者手动配置,但是需要在苹果开发者后台,对开发及发布证书勾选相应能力,再生成podfile文件。
> 2.在iOS13及以上系统,获取当前连接的WiFi信息需要先获取系统定位权限,因此在iOS13及以上系统使用此接口时,会触发定位权限申请的弹窗。
### uni.startWifi
初始化WiFi模块。
**注意平台差异:iOS暂不支持此接口**
### uni.stopWifi
停止WiFi模块。
**注意平台差异:iOS暂不支持此接口**
### uni.getWifiList
获取WiFi列表。
**注意平台差异:iOS暂不支持此接口**
### uni.onGetWifiList
获取WiFi列表的回调。
**注意平台差异:iOS暂不支持此接口**
### uni.offGetWifiList
注销获取WiFi列表的回调。
**注意平台差异:iOS暂不支持此接口**
### uni.connectWifi
连接指定WiFi。
**注意平台差异:iOS暂不支持此接口**
### uni.onWifiConnected
连上wifi事件的监听函数。
**注意平台差异:iOS暂不支持此接口**
### uni.onWifiConnectedWithPartialInfo
连上wifi事件的监听函数, wifiInfo仅包含SSID。
**注意平台差异:iOS暂不支持此接口**
### uni.offWifiConnected
移除连接上wifi的事件的监听函数,不传此参数则移除所有监听函数。
**注意平台差异:iOS暂不支持此接口**
### uni.onOffWifiConnectedWithPartialInfo
移除连接上wifi的事件的监听函数,不传参数则移除所有监听函数。
**注意平台差异:iOS暂不支持此接口**
### uni.setWifiList
设置 wifiList 中 AP 的相关信息。在 onGetWifiList 回调后调用,iOS特有接口。
**注意平台差异:iOS特有接口,目前暂未支持**
import WifiManager from "android.net.wifi.WifiManager";
import WifiConfiguration from 'android.net.wifi.WifiConfiguration';
function isHexWepKey(wepKey:String):boolean {
let len = wepKey.length();
// WEP-40, WEP-104, and some vendors using 256-bit WEP (WEP-232?)
if (len != 10 && len != 26 && len != 58) {
return false;
}
return isHex(wepKey);
}
function isHex(key:string):boolean {
for (var i = key.length() - 1; i >= 0; i--) {
let c = key.charAt(i);
if (!(c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a'
&& c <= 'f')) {
return false;
}
}
return true;
}
// 查看以前是否也配置过这个网络
function isExsits(SSID:string ,wifiManager:WifiManager):WifiConfiguration | null{
let existingConfigs = wifiManager.getConfiguredNetworks();
for (let existingConfig in existingConfigs) {
if (existingConfig.SSID.equals("\" + SSID + "\")) {
return existingConfig;
}
}
return null;
}
function createWifiInfo(SSID:string ,password:string):WifiConfiguration {
let config = new WifiConfiguration();
config.allowedAuthAlgorithms.clear();
config.allowedGroupCiphers.clear();
config.allowedKeyManagement.clear();
config.allowedPairwiseCiphers.clear();
config.allowedProtocols.clear();
config.SSID = "\"" + SSID + "\"";
// // nopass
// // if (Type == WifiCipherType.WIFICIPHER_NOPASS) {
// // config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
// // }
// // // wep
// // if (Type == WifiCipherType.WIFICIPHER_WEP) {
// if (!TextUtils.isEmpty(Password)) {
// if (isHexWepKey(Password)) {
// config.wepKeys[0] = Password;
// } else {
// config.wepKeys[0] = "\"" + Password + "\"";
// }
// }
// config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
// config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED);
// config.allowedKeyManagement.set(KeyMgmt.NONE);
// config.wepTxKeyIndex = 0;
// // }
// // wpa
// if (Type == WifiCipherType.WIFICIPHER_WPA) {
// config.preSharedKey = "\"" + Password + "\"";
// config.hiddenSSID = true;
// config.allowedAuthAlgorithms
// .set(WifiConfiguration.AuthAlgorithm.OPEN);
// config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
// config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
// config.allowedPairwiseCiphers
// .set(WifiConfiguration.PairwiseCipher.TKIP);
// // 此处需要修改否则不能自动重联
// // config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
// config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
// config.allowedPairwiseCiphers
// .set(WifiConfiguration.PairwiseCipher.CCMP);
// config.status = WifiConfiguration.Status.ENABLED;
// }
return config;
}
class ConnectRunnable extends Runnable {
ssid:string = ""
password:string = ""
constructor(ssid:string,password:string) {
this.ssid = ssid
this.password = password
}
override run():void{
try {
// 打开wifi wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING
WifiConfiguration wifiConfig = createWifiInfo(ssid, password,
type);
WifiConfiguration tempConfig = isExsits(ssid);
if (tempConfig != null) {
wifiManager.removeNetwork(tempConfig.networkId);
}
int netID = wifiManager.addNetwork(wifiConfig);
boolean enabled = wifiManager.enableNetwork(netID, true);
boolean connected = wifiManager.reconnect();
} catch (Exception e) {
// TODO: handle exception
sendMsg(e.getMessage());
e.printStackTrace();
}
}
}
class WifiConnector {
wifiManager:WifiManager;
//WIFICIPHER_WEP是WEP ,WIFICIPHER_WPA是WPA,WIFICIPHER_NOPASS没有密码
// enum WifiCipherType {
// WIFICIPHER_WEP, WIFICIPHER_WPA, WIFICIPHER_NOPASS, WIFICIPHER_INVALID
// }
// 构造函数
constructor(wifiManager:WifiManager) {
this.wifiManager = wifiManager;
}
// 提供一个外部接口,传入要连接的无线网
connect(ssid:string ,password:string) {
Thread thread = new Thread(new ConnectRunnable(ssid,password));
thread.start();
}
}
import Context from "android.content.Context";
import { getAppContext, getUniActivity } from "io.dcloud.uts.android";
import { UTSAndroid } from "io.dcloud.uts";
import WifiManager from "android.net.wifi.WifiManager";
import WifiInfo from "android.net.wifi.WifiInfo";
import Manifest from "android.Manifest";
......@@ -12,7 +12,11 @@ import Gson from "com.google.gson.Gson";
import JSONObject from "com.alibaba.fastjson.JSONObject";
import Intent from "android.content.Intent";
import Thread from "java.lang.Thread";
import WifiConfiguration from 'android.net.wifi.WifiConfiguration';
import AuthAlgorithm from 'android.net.wifi.WifiConfiguration.AuthAlgorithm';
import KeyMgmt from 'android.net.wifi.WifiConfiguration.KeyMgmt';
import TextUtils from 'android.text.TextUtils';
/**
* Wifi 函数通用入参封装
......@@ -23,6 +27,8 @@ type WifiOption = {
complete?: (res: object) => void;
};
/**
* Wifi 链接参数封装
*/
......@@ -35,14 +41,39 @@ type WifiConnectOption = {
success?: (res: object) => void;
fail?: (res: object) => void;
complete?: (res: object) => void;
}
/**
* 是否是标准的16进制字符
*/
function isHex(key:string):boolean {
for (var i = key.length - 1; i >= 0; i--) {
let c = key.charAt(i);
if (!(c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a'
&& c <= 'f')) {
return false;
}
}
return true;
}
/**
* 判断是否是wep格式的key
*/
function isHexWepKey(wepKey:string):boolean {
let len = wepKey.length;
// WEP-40, WEP-104, and some vendors using 256-bit WEP (WEP-232?)
if (len != 10 && len != 26 && len != 58) {
return false;
}
function wrapWifiConfiguration(SSID:string ,password:string):WifiConfiguration {
return isHex(wepKey);
}
@Suppress("DEPRECATION")
function wrapWifiConfiguration(SSID:string ,password:string,passwordType:string):WifiConfiguration {
let config = new WifiConfiguration();
......@@ -53,6 +84,43 @@ function wrapWifiConfiguration(SSID:string ,password:string):WifiConfiguration {
config.allowedProtocols.clear();
config.SSID = "\"" + SSID + "\"";
// nopass
if ("NONE".equals(passwordType)) {
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
}
// // wep
if ("WEP".equals(passwordType)) {
if (!TextUtils.isEmpty(password)) {
if (isHexWepKey(password)) {
config.wepKeys[0] = password;
} else {
config.wepKeys[0] = "\"" + password + "\"";
}
}
config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED);
config.allowedKeyManagement.set(KeyMgmt.NONE);
config.wepTxKeyIndex = 0;
}
// wpa
if ("WPA".equals(passwordType)) {
config.preSharedKey = "\"" + password + "\"";
config.hiddenSSID = true;
config.allowedAuthAlgorithms
.set(WifiConfiguration.AuthAlgorithm.OPEN);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
config.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.TKIP);
// 此处需要修改否则不能自动重联
config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
config.allowedPairwiseCiphers
.set(WifiConfiguration.PairwiseCipher.CCMP);
config.status = WifiConfiguration.Status.ENABLED;
}
return config;
}
/**
......@@ -137,9 +205,10 @@ type GetConnectedWifiOptions = {
*/
class Global {
static mReceiver?: CustomBroadcastReceiver = null;
static scanList: UniWifiInfo[] = []
static WIFI_AUTH_OPEN: String = "";
static WIFI_AUTH_ROAM: String = "[ESS]";
static scanList: UniWifiInfo[] = []
static getWifiListCallbackList: UTSCallback[] = []
static onWifiConnectCallbackList: UTSCallback[] = []
}
......@@ -160,6 +229,7 @@ function getSecurityType(result:ScanResult):string {
/**
* 自定义wifi变化广播监听器
*/
@Suppress("UNUSED_PARAMETER","DEPRECATION")
class CustomBroadcastReceiver extends BroadcastReceiver {
mWifiManager?: WifiManager = null;
......@@ -224,8 +294,8 @@ class CustomBroadcastReceiver extends BroadcastReceiver {
for (let perCallback in Global.getWifiListCallbackList) {
const data = new JSONObject();
let mainJsonStr = Gson().toJson(Global.scanList);
data["wifiList"] = mainJsonStr
// let mainJsonStr = Gson().toJson(Global.scanList);
data["wifiList"] = Global.scanList
perCallback(data);
}
......@@ -243,6 +313,7 @@ class CustomBroadcastReceiver extends BroadcastReceiver {
/**
* 获取wifi列表
*/
@Suppress("DEPRECATION")
export function getWifiList(option: WifiOption) {
if (Global.mReceiver == null) {
......@@ -259,7 +330,7 @@ export function getWifiList(option: WifiOption) {
}
let wifiManager: WifiManager =
getAppContext()!.getSystemService(Context.WIFI_SERVICE) as WifiManager
UTSAndroid.getAppContext()!.getSystemService(Context.WIFI_SERVICE) as WifiManager
wifiManager.startScan()
let ret = {
......@@ -310,10 +381,10 @@ export function offGetWifiList(callback: UTSCallback) {
/**
* 链接指定wifi
*/
@Suppress("UNUSED_PARAMETER","DEPRECATION")
export function connectWifi(option: WifiConnectOption) {
var result = {
errCode: 12000,
errMsg: "connectWifi:fail:not invoke startWifi",
......@@ -328,20 +399,18 @@ export function connectWifi(option: WifiConnectOption) {
return
}
// if(option.maunal == true){
// // 指定了手动模式
// let manunalIntent = new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS);
// getUniActivity()!!.startActivity(manunalIntent);
// result.errCode = 0
// result.errMsg = "connectWifi:ok"
if(option.maunal == true){
// 指定了手动模式
let manunalIntent = new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS);
UTSAndroid.getUniActivity()!.startActivity(manunalIntent);
// option.success
result.errCode = 0
result.errMsg = "connectWifi:ok"
// ?.(result)
// option.complete?.(result)
// return
// }
option.success?.(result)
option.complete?.(result)
return
}
// 执行后续的逻辑
let scanWifiInfo:UniWifiInfo|null = null
......@@ -360,13 +429,14 @@ export function connectWifi(option: WifiConnectOption) {
return
}
console.log(scanWifiInfo);
console.log(JSON.stringify(scanWifiInfo.securityType));
let wifiConfigration = wrapWifiConfiguration(option.SSID,option.password);
let wifiConfigration = wrapWifiConfiguration(option.SSID,option.password,scanWifiInfo.securityType);
let wifiManager: WifiManager =
getAppContext()!.getSystemService(Context.WIFI_SERVICE) as WifiManager
UTSAndroid.getAppContext()!.getSystemService(Context.WIFI_SERVICE) as WifiManager
// 如果已经存在了指定wifi 配置,移除之
let targetExistConfig:WifiConfiguration|null = null
let existingConfigs = wifiManager.getConfiguredNetworks();
for (let existingConfig in existingConfigs) {
......@@ -379,12 +449,24 @@ export function connectWifi(option: WifiConnectOption) {
wifiManager.removeNetwork(targetExistConfig.networkId);
}
let netID = wifiManager.addNetwork(wifiConfigration);
let enabled = wifiManager.enableNetwork(netID, true);
let connected = wifiManager.reconnect();
try {
let netID = wifiManager.addNetwork(wifiConfigration);
let enabled = wifiManager.enableNetwork(netID, true);
let connected = wifiManager.reconnect();
console.log(enabled);
console.log(connected);
} catch (e) {
// TODO: handle exception
console.log(e);
// e.printStackTrace();
}
console.log(connected);
result.errCode = 0
result.errMsg = "connectWifi:ok"
option.success?.(result)
option.complete?.(result)
}
......@@ -392,21 +474,21 @@ export function connectWifi(option: WifiConnectOption) {
/**
* 开启wifi
*/
@Suppress("DEPRECATION")
export function startWifi(option: WifiOption) {
// 需要先开启wifi,才能使用后续的功能
let requestCode = 1001;
let permissionWifi = arrayOf("android.permission.ACCESS_FINE_LOCATION");
var result = {
errCode: 12001,
errMsg: "startWifi:premission loss"
errMsg: "startWifi:premission loss",
errSubject:"uni-startWifi"
}
// 检查权限
if (ActivityCompat.checkSelfPermission(getUniActivity()!, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.checkSelfPermission(UTSAndroid.getUniActivity()!, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getUniActivity()!, permissionWifi, requestCode)
ActivityCompat.requestPermissions(UTSAndroid.getUniActivity()!, permissionWifi, requestCode)
// 尚不具备权限,返回错误
option.fail?.(result)
option.complete?.(result)
......@@ -416,7 +498,7 @@ export function startWifi(option: WifiOption) {
// 具备了权限,继续前进
let wifiManager: WifiManager =
getAppContext()!.getSystemService(Context.WIFI_SERVICE) as WifiManager
UTSAndroid.getAppContext()!.getSystemService(Context.WIFI_SERVICE) as WifiManager
if (Global.mReceiver == null) {
Global.mReceiver = new CustomBroadcastReceiver(wifiManager)
......@@ -429,7 +511,27 @@ export function startWifi(option: WifiOption) {
// @ts-ignore
filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
getUniActivity()!.registerReceiver(Global.mReceiver, filter)
UTSAndroid.getUniActivity()!.registerReceiver(Global.mReceiver, filter)
/**
* activity 被销毁时,取消注册
*/
UTSAndroid.onAppActivityDestroy(function(){
if(Global.mReceiver!= null){
UTSAndroid.getUniActivity()!.unregisterReceiver(Global.mReceiver)
Global.mReceiver = null
Global.scanList = []
Global.getWifiListCallbackList = []
Global.onWifiConnectCallbackList = []
console.log("UTSAndroid.getUniActivity() == " + UTSAndroid.getUniActivity());
console.log("Global.mReceiver == " + Global.mReceiver);
}
});
wifiManager.startScan()
result.errCode = 0
result.errMsg = "startWifi:ok"
......@@ -456,8 +558,13 @@ export function stopWifi(option: WifiOption) {
return
}
getUniActivity()!.unregisterReceiver(Global.mReceiver)
try{
UTSAndroid.getUniActivity()!.unregisterReceiver(Global.mReceiver)
}catch(e){
// 多次调用
//TODO handle the exception
}
var result = {
errNo: 0,
errCode: 0,
......@@ -471,6 +578,7 @@ export function stopWifi(option: WifiOption) {
/**
* 获取当前连接中的wifi信息
*/
@Suppress("DEPRECATION")
export function getConnectedWifi(option: GetConnectedWifiOptions) {
let wifiInfo = new UniWifiInfo(null)
......@@ -478,6 +586,7 @@ export function getConnectedWifi(option: GetConnectedWifiOptions) {
var res = {
errCode: 12000,
errMsg: "getConnectedWifi:fail:not invoke startWifi",
errSubject:"uni-getConnectedWifi",
wifi:wifiInfo
}
......@@ -489,7 +598,7 @@ export function getConnectedWifi(option: GetConnectedWifiOptions) {
return
}
if (ActivityCompat.checkSelfPermission(getUniActivity()!, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.checkSelfPermission(UTSAndroid.getUniActivity()!, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// 尚不具备权限,返回错误
res.errCode = 12001
res.errMsg = "getConnectedWifi:permission loss"
......@@ -501,7 +610,7 @@ export function getConnectedWifi(option: GetConnectedWifiOptions) {
// TODO 应该try catch一下,把系统的错误码给返回来,然后和微信的错误码拉齐
// 需要先校验权限,没有位置权限无法获取wifi
const context = getAppContext();
const context = UTSAndroid.getAppContext();
if (context != null) {
const wm = context.getSystemService(
Context.WIFI_SERVICE
......
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSLocationWhenInUseUsageDescription</key>
<string>使用期间获取位置权限</string>
</dict>
</plist>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.developer.networking.wifi-info</key>
<true/>
</dict>
</plist>
\ No newline at end of file
{
"frameworks": [
"CoreLocation",
"SystemConfiguration"
],
"deploymentTarget": "9.0",
"validArchitectures": [
"arm64", "armv7" ]
}
\ No newline at end of file
import { CLLocationManager, CLAuthorizationStatus, CLLocationManagerDelegate } from 'CoreLocation'
import { CaptiveNetwork, kCNNetworkInfoKeySSID, kCNNetworkInfoKeyBSSID } from 'SystemConfiguration.CaptiveNetwork';
import { NSArray, NSDictionary } from 'Foundation';
import { CFString } from 'CoreFoundation';
import { UIDevice } from 'UIKit';
/**
* Wifi 函数通用入参封装
*/
type WifiOption = {
success?: (res: object) => void;
fail?: (res: object) => void;
complete?: (res: object) => void;
};
/**
* Wifi 链接参数封装
*/
type WifiConnectOption = {
SSID: string;
BSSID: string;
password: string;
maunal: boolean;
partialInfo: boolean; //ios不生效
success?: (res: object) => void;
fail?: (res: object) => void;
complete?: (res: object) => void;
}
/**
* 获取当前链接的wifi信息
*/
type GetConnectedWifiOptions = {
partialInfo?: boolean
success?: (res: UTSJSONObject) => void
fail?: (res: UTSJSONObject) => void
complete?: (res: UTSJSONObject) => void
}
/*
* 对外暴露的wifi信息
*/
type UniWifiInfo = {
SSID: string;
BSSID: string;
secure: boolean;
signalStrength: number;
frequency: number;
}
/*
* 系统定位权限获取类
*/
class LocationPromiseService implements CLLocationManagerDelegate {
static promiseCompletionHandler: ((res: boolean)=>void)[] = []
manager?: CLLocationManager
constructor(manager?: CLLocationManager) {
this.manager = manager
}
initlizeManager(): boolean {
if (this.manager == null) {
this.manager = new CLLocationManager()
this.manager!.delegate = this
}
return true
}
locationManager(manager: CLLocationManager, status: CLAuthorizationStatus) {
if (status == CLAuthorizationStatus.authorizedAlways || status == CLAuthorizationStatus.authorizedWhenInUse) {
LocationPromiseService.promiseCompletionHandler.forEach((handler): void => {
handler(true)
})
} else if (status == CLAuthorizationStatus.notDetermined) {
manager.requestWhenInUseAuthorization()
} else if (status == CLAuthorizationStatus.denied) {
LocationPromiseService.promiseCompletionHandler.forEach((handler): void => {
handler(false)
})
}
}
locationManagerDidChangeAuthorization(manager: CLLocationManager) {
}
locationManagerDidPauseLocationUpdates(manager: CLLocationManager) {
}
locationManagerDidResumeLocationUpdates(manager: CLLocationManager) {
}
locationManagerShouldDisplayHeadingCalibration(manager: CLLocationManager): boolean {
return true
}
requestPromise(@escaping completion: (res: boolean)=>void) {
let status: CLAuthorizationStatus = CLLocationManager.authorizationStatus()
if (status == CLAuthorizationStatus.notDetermined) {
if (this.initlizeManager() == true) {
this.manager!.requestWhenInUseAuthorization()
LocationPromiseService.promiseCompletionHandler.push(completion)
}
} else if (status == CLAuthorizationStatus.authorizedAlways || status == CLAuthorizationStatus.authorizedWhenInUse) {
completion(true)
} else if (status == CLAuthorizationStatus.denied) {
if (CLLocationManager.locationServicesEnabled() == false && this.initlizeManager() == true) {
this.manager!.requestWhenInUseAuthorization()
LocationPromiseService.promiseCompletionHandler.push(completion)
}
}
}
}
const locationPromiseService: LocationPromiseService = new LocationPromiseService(null)
/*
* 获取系统定位权限
*/
function requestLocationPromise(@escaping completion: (res: boolean)=>void) {
locationPromiseService.requestPromise(completion)
}
/*
* 获取当前连接的wifi信息(通过定位权限)
*/
function fetchConnectedWifiWithLocationPromise(option: GetConnectedWifiOptions) {
let arr = CNCopySupportedInterfaces()
let wifiInfo = new UniWifiInfo()
if (arr != null) {
let list = arr! as NSArray
let index = 0
while (index < list.count) {
let item = list[index]
let interfaceName = item as string
let dic = CNCopyCurrentNetworkInfo(interfaceName as CFString)
if (dic != null) {
let dict = dic! as NSDictionary
let SSID = dict[kCNNetworkInfoKeySSID as string]
let BSSID = dict[kCNNetworkInfoKeyBSSID as string]
if (SSID != null && BSSID != null) {
let ssid = SSID! as string
let bssid = BSSID! as string
wifiInfo.SSID = ssid
wifiInfo.BSSID = bssid
wifiInfo.signalStrength = 0
wifiInfo.frequency = 0
break;
}
}
index++
}
if (wifiInfo.BSSID.length > 0 && wifiInfo.SSID.length > 0) {
let res = {
errCode: 0,
errMsg: "getConnectedWifi:success",
wifi: wifiInfo,
}
option.success?.(res)
option.complete?.(res)
}else {
option.fail?.({errCode: 12000, errMsg: "current wifi is null"})
option.complete?.({errCode: 12000, errMsg: "current wifi is null"})
}
}else {
option.fail?.({errCode: 12000, errMsg: "current wifi is null"})
option.complete?.({errCode: 12000, errMsg: "current wifi is null"})
}
}
/* =================================== 对外暴露的接口 ==============================================*/
/*
* 初始化wifi模块
*/
export function startWifi(option: WifiOption) {
let res = {
errCode: 12001,
errMsg: "system not support"
}
option.fail?.(res)
option.complete?.(res)
}
/*
* 停止wifi模块
*/
export function stopWifi() {
LocationPromiseService.promiseCompletionHandler = []
}
/*
* 获取wifi列表, 在调用之前需要引导用户跳转到系统设置-WIFI设置页面,系统搜索周边wifi后app才能接收到回调
*/
export function getWifiList(option: WifiOption) {
let res = {
errCode: 12001,
errMsg: "system not support"
}
option.fail?.(res)
option.complete?.(res)
}
/* 获取wifi列表的回调
* note: 请在getWifiList方法的回调里调用该方法
*/
export function onGetWifiList(callback: UTSCallback) {
}
/*
* 注销获取wifi列表的回调
*/
export function offGetWifiList(callback: UTSCallback) {
}
/*
* 获取当前连接的wifi信息
*/
export function getConnectedWifi(option: GetConnectedWifiOptions) {
if (UIDevice.current.systemVersion >= "13.0") {
requestLocationPromise((success) => {
if (success == true) {
fetchConnectedWifiWithLocationPromise(option)
}else {
let res = {
errCode: 12010,
errMsg: "have no location promise"
}
option.fail?.(res)
option.complete?.(res)
}
})
} else{
fetchConnectedWifiWithLocationPromise(option)
}
}
/*
* 连接wifi
*/
export function connectWifi(option: WifiConnectOption) {
let res = {
errCode: 12001,
errMsg: "system not support"
}
option.fail?.(res)
option.complete?.(res)
}
/*
* 连上wifi事件的监听函数
*/
export function onWifiConnected(callback: UTSCallback) {
}
/*
* 连上wifi事件的监听函数, wifiInfo仅包含ssid
*/
export function onWifiConnectedWithPartialInfo(callback: UTSCallback) {
}
/*
* 移除连接上wifi的事件的监听函数,不传此参数则移除所有监听函数。
*/
export function offWifiConnected(callback: UTSCallback | null) {
}
/*
* 移除连接上wifi的事件的监听函数,不传此参数则移除所有监听函数。
*/
export function onOffWifiConnectedWithPartialInfo(callback: UTSCallback | null) {
}
/*
* 设置 wifiList 中 AP 的相关信息。在 onGetWifiList 回调后调用,iOS特有接口。
*/
export function setWifiList(option: WifiOption) {
let res = {
errCode: 12001,
errMsg: "system not support"
}
option.fail?.(res)
option.complete?.(res)
}
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册