提交 a9e7667c 编写于 作者: DCloud_iOS_WZT's avatar DCloud_iOS_WZT

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

# Conflicts:
#	uni_modules/uni-usercapturescreen/package.json
module.exports = {
testTimeout: 10000,
reporters: [
'default'
],
watchPathIgnorePatterns: ['/node_modules/', '/dist/', '/.git/'],
moduleFileExtensions: ['js', 'json'],
rootDir: __dirname,
testMatch: ["<rootDir>/pages/**/*test.[jt]s?(x)"],
testPathIgnorePatterns: ['/node_modules/']
}
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
"style": { "style": {
"navigationBarTitleText": "uni-app" "navigationBarTitleText": "uni-app"
} }
} }
], ],
"globalStyle": { "globalStyle": {
"navigationBarTextStyle": "black", "navigationBarTextStyle": "black",
......
<template> <template>
<view class="content"> <view class="content">
<image class="logo" src="/static/logo.png"></image>
<view class="text-area">
<text class="title">{{title}}</text> <button @tap="testStartWifi" style="width: 100%;">初始化wifi模块</button>
</view> <button @tap="testGetWifiList" style="width: 100%;">获取当前wifi列表</button>
<button @tap="testOffGetWifiList" style="width: 100%;">移除wifi列表监听</button>
<button @tap="testGetConnnectWifi" style="width: 100%;">获取当前连接的wifi</button>
<button @tap="testConnnectWifi" style="width: 100%;">链接wifi</button>
<button @tap="testStopWifi" style="width: 100%;">关闭wifi模块</button>
<button @tap="onGetWifiList2_assert0" style="width: 100%;">onGetWifiList2_assert0</button>
<button @tap="testScreenShotListen">开启截屏监听</button> <button @tap="testScreenShotListen">开启截屏监听</button>
<button @tap="testScreenShotOff">关闭截屏监听</button> <button @tap="testScreenShotOff">关闭截屏监听</button>
<button @tap="testSetUserCaptureScreen">{{setUserCaptureScreenText}}</button> <button @tap="testSetUserCaptureScreen">{{setUserCaptureScreenText}}</button>
...@@ -12,11 +19,7 @@ ...@@ -12,11 +19,7 @@
<button @tap="testonMemoryWarning">开启内存不足告警监听</button> <button @tap="testonMemoryWarning">开启内存不足告警监听</button>
<button @tap="testoffMemoryWarning">关闭内存不足告警监听</button> <button @tap="testoffMemoryWarning">关闭内存不足告警监听</button>
<button @tap="testStartWifi">初始化wifi模块</button>
<button @tap="testGetWifiList">获取当前wifi列表</button>
<button @tap="testGetConnnectWifi">获取当前连接的wifi</button>
<button @tap="testConnnectWifi">链接wifi</button>
<button @tap="testStopWifi">关闭wifi模块</button>
</view> </view>
</template> </template>
...@@ -25,7 +28,6 @@ ...@@ -25,7 +28,6 @@
export default { export default {
data() { data() {
return { return {
title: 'Hello',
memListener:null, memListener:null,
setUserCaptureScreenFlag: false, setUserCaptureScreenFlag: false,
setUserCaptureScreenText: '禁止截屏', setUserCaptureScreenText: '禁止截屏',
...@@ -39,16 +41,49 @@ ...@@ -39,16 +41,49 @@
onMemoryWarning:function(res){ onMemoryWarning:function(res){
console.log(res); console.log(res);
}, },
fn:function(res){
console.log(res)
},
onGetWifiList2_assert0() {
const fn = res => console.log('onGetWifiList res', res)
uni.startWifi({success(){
uni.onGetWifiList(fn)
uni.getWifiList({
success() {
console.log('getWifiList success');
uni.offGetWifiList(fn)
uni.stopWifi({
success() {},
fail(e) {
console.log("stopWifi fail: ",e);
}
})
}
})
}})
},
testConnnectWifi(){ testConnnectWifi(){
uni.connectWifi({ uni.startWifi({
maunal:false, success:(res)=> {
SSID:"Xiaomi_20D0", console.log("success: " + JSON.stringify(res));
password:"BBBB", // uni.connectWifi({
complete:(res)=>{ // maunal:false,
console.log(res); // SSID:"Xiaomi_20D0",
// password:"BBB111",
// complete:(res)=>{
// console.log(res);
// }
// });
},fail:(res)=>{
console.log("fail: " + JSON.stringify(res));
},complete:(res)=>{
console.log("complete: " + JSON.stringify(res));
} }
}); })
}, },
testGetConnnectWifi(){ testGetConnnectWifi(){
...@@ -97,6 +132,9 @@ ...@@ -97,6 +132,9 @@
}) })
}, },
testStopWifi() { testStopWifi() {
uni.offWifiConnected()
uni.offWifiConnectedWithPartialInfo()
uni.stopWifi({ uni.stopWifi({
success:(res)=> { success:(res)=> {
console.log("success: " + JSON.stringify(res)); console.log("success: " + JSON.stringify(res));
...@@ -120,6 +158,13 @@ ...@@ -120,6 +158,13 @@
}) })
}, },
testOffGetWifiList(){
uni.offGetWifiList()
},
testonMemoryWarning() { testonMemoryWarning() {
uni.onMemoryWarning(this.onMemoryWarning) uni.onMemoryWarning(this.onMemoryWarning)
uni.showToast({ uni.showToast({
......
## 1.0.4(2023-03-24)
新增开启/关闭防截屏功能
## 1.0.3(2023-03-17)
修复android平台 部分场景下js可能报错的问题
## 1.0.2(2023-03-16)
修复Android平台在小米设备无法监听的问题 修复Android平台调用uni.onUserCaptureScreen必然会触发回调的问题
## 1.0.1(2022-10-27) ## 1.0.1(2022-10-27)
修改插件描述 修改插件描述
## 1.0.0(2022-10-26) ## 1.0.0(2022-10-26)
......
{ {
"id": "uni-usercapturescreen", "id": "uni-usercapturescreen",
"displayName": "uni-usercapturescreen", "displayName": "uni-usercapturescreen",
"version": "1.0.1", "version": "1.0.4",
"description": "用户主动截屏事件监听", "description": "用户主动截屏事件监听",
"keywords": [ "keywords": [
"截屏" "截屏"
], ],
"repository": "", "repository": "",
"engines": { "engines": {
"HBuilderX": "^3.6.8" "HBuilderX": "^3.7.7"
}, },
"dcloudext": { "dcloudext": {
"type": "uts", "type": "uts",
...@@ -47,7 +47,7 @@ ...@@ -47,7 +47,7 @@
}, },
"client": { "client": {
"Vue": { "Vue": {
"vue2": "y", "vue2": "n",
"vue3": "y" "vue3": "y"
}, },
"App": { "App": {
......
...@@ -13,3 +13,9 @@ ...@@ -13,3 +13,9 @@
用户主动截屏事件。取消事件监听。 用户主动截屏事件。取消事件监听。
> 使用文档:[https://uniapp.dcloud.net.cn/api/system/capture-screen.html#offusercapturescreen](https://uniapp.dcloud.net.cn/api/system/capture-screen.html#offusercapturescreen) > 使用文档:[https://uniapp.dcloud.net.cn/api/system/capture-screen.html#offusercapturescreen](https://uniapp.dcloud.net.cn/api/system/capture-screen.html#offusercapturescreen)
### uni.setUserCaptureScreen
开启/关闭防截屏。
> 使用文档:[https://uniapp.dcloud.net.cn/api/system/capture-screen.html#setusercapturescreen](https://uniapp.dcloud.net.cn/api/system/capture-screen.html#setusercapturescreen)
...@@ -19,8 +19,8 @@ export type UserCaptureScreenCallback = (res : OnUserCaptureScreenCallbackResult ...@@ -19,8 +19,8 @@ export type UserCaptureScreenCallback = (res : OnUserCaptureScreenCallbackResult
* *
* @param {UserCaptureScreenCallback} callback * @param {UserCaptureScreenCallback} callback
* @tutorial https://uniapp.dcloud.net.cn/api/system/capture-screen.html#onusercapturescreen * @tutorial https://uniapp.dcloud.net.cn/api/system/capture-screen.html#onusercapturescreen
* @platforms APP-IOS = ^9.0,APP-ANDROID = ^19 * @platforms APP-IOS = ^9.0,APP-ANDROID = ^4.4
* @since 3.6.8 * @since 3.7.7
*/ */
export type OnUserCaptureScreen = (callback : UserCaptureScreenCallback | null) => void export type OnUserCaptureScreen = (callback : UserCaptureScreenCallback | null) => void
...@@ -30,8 +30,8 @@ export type OnUserCaptureScreen = (callback : UserCaptureScreenCallback | null) ...@@ -30,8 +30,8 @@ export type OnUserCaptureScreen = (callback : UserCaptureScreenCallback | null)
* *
* @param {UserCaptureScreenCallback} callback * @param {UserCaptureScreenCallback} callback
* @tutorial https://uniapp.dcloud.net.cn/api/system/capture-screen.html#offusercapturescreen * @tutorial https://uniapp.dcloud.net.cn/api/system/capture-screen.html#offusercapturescreen
* @platforms APP-IOS = ^9.0,APP-ANDROID = ^19 * @platforms APP-IOS = ^9.0,APP-ANDROID = ^4.4
* @since 3.6.8 * @since 3.7.7
*/ */
export type OffUserCaptureScreen = (callback : UserCaptureScreenCallback | null) => void export type OffUserCaptureScreen = (callback : UserCaptureScreenCallback | null) => void
...@@ -47,8 +47,6 @@ export type SetUserCaptureScreenSuccess = { ...@@ -47,8 +47,6 @@ export type SetUserCaptureScreenSuccess = {
export type SetUserCaptureScreenFail = { export type SetUserCaptureScreenFail = {
/** /**
* 错误码 * 错误码
* 0:成功
* -1:permission denied
* 12001:system not support * 12001:system not support
* 12010:system internal error * 12010:system internal error
*/ */
...@@ -112,12 +110,12 @@ export type SetUserCaptureScreenOptions = { ...@@ -112,12 +110,12 @@ export type SetUserCaptureScreenOptions = {
* *
* @param {SetUserCaptureScreenOptions} options * @param {SetUserCaptureScreenOptions} options
* @tutorial https://uniapp.dcloud.net.cn/api/system/capture-screen.html#setusercapturescreen * @tutorial https://uniapp.dcloud.net.cn/api/system/capture-screen.html#setusercapturescreen
* @platforms APP-IOS = ^13.0,APP-ANDROID = ^19 * @platforms APP-IOS = ^13.0,APP-ANDROID = ^4.4
* @since 3.7.3 * @since 3.7.7
*/ */
export type SetUserCaptureScreen = (options : SetUserCaptureScreenOptions) => void export type SetUserCaptureScreen = (options : SetUserCaptureScreenOptions) => void
interface uni { export interface Uni {
onUserCaptureScreen : OnUserCaptureScreen, onUserCaptureScreen : OnUserCaptureScreen,
offUserCaptureScreen : OffUserCaptureScreen, offUserCaptureScreen : OffUserCaptureScreen,
setUserCaptureScreen : SetUserCaptureScreen setUserCaptureScreen : SetUserCaptureScreen
......
...@@ -16,69 +16,39 @@ import WifiConfiguration from 'android.net.wifi.WifiConfiguration'; ...@@ -16,69 +16,39 @@ import WifiConfiguration from 'android.net.wifi.WifiConfiguration';
import AuthAlgorithm from 'android.net.wifi.WifiConfiguration.AuthAlgorithm'; import AuthAlgorithm from 'android.net.wifi.WifiConfiguration.AuthAlgorithm';
import KeyMgmt from 'android.net.wifi.WifiConfiguration.KeyMgmt'; import KeyMgmt from 'android.net.wifi.WifiConfiguration.KeyMgmt';
import TextUtils from 'android.text.TextUtils'; import TextUtils from 'android.text.TextUtils';
import Build from 'android.os.Build';
/** import { UniWifiResult, GetConnectedWifiOptions, WifiConnectOption, WifiOption, UniWifiInfo } from "../interface.uts"
* Wifi 函数通用入参封装
*/
type WifiOption = {
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 WifiConnectOption = {
SSID:string;
BSSID?:string;
password:string;
maunal:boolean;
// 只返回ssid
partialInfo:boolean;
success?: (res: object) => void;
fail?: (res: object) => void;
complete?: (res: object) => void;
}
/**
* 全局数据储存
*/
class Global { class Global {
static mReceiver: CustomBroadcastReceiver|null = null; static mReceiver : CustomBroadcastReceiver | null = null;
static WIFI_AUTH_OPEN: string = ""; static WIFI_AUTH_OPEN : string = "";
static WIFI_AUTH_ROAM: String = "[ESS]"; static WIFI_AUTH_ROAM : String = "[ESS]";
// 扫描wifi结果 // 扫描wifi结果
static scanList: UniWifiInfo[] = [] static scanList : AndroidUniWifiInfo[] = []
// 获取wifi列表监听 // 获取wifi列表监听
static getWifiListCallbackList: UTSCallback[] = [] static onGetWifiListCallback : UTSCallback | null = null
static supendGetWifiSuccess : ((res: UniWifiResult) => void) | null = null
static supendGetWifiComplete : ((res: UniWifiResult) => void) | null = null
// wifi链接监听 // wifi链接监听
static onWifiConnectCallbackList: UTSCallback[] = [] static onWifiConnectCallbackList : UTSCallback[] = []
static onWifiConnectWithPartialInfoCallbackList: UTSCallback[] = [] static onWifiConnectWithPartialInfoCallbackList : UTSCallback[] = []
} }
/** /**
* 是否是标准的16进制字符 * 是否是标准的16进制字符
*/ */
function isHex(key:string):boolean { function isHex(key : string) : boolean {
for (var i = key.length - 1; i >= 0; i--) { for (var i = key.length - 1; i >= 0; i--) {
let c = key.charAt(i); let c = key.charAt(i);
if (!(c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a' if (!(c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a'
&& c <= 'f')) { && c <= 'f')) {
return false; return false;
} }
} }
...@@ -87,9 +57,9 @@ function isHex(key:string):boolean { ...@@ -87,9 +57,9 @@ function isHex(key:string):boolean {
} }
/** /**
* 判断是否是wep格式的key * 判断是否是wep格式的key
*/ */
function isHexWepKey(wepKey:string):boolean { function isHexWepKey(wepKey : string) : boolean {
let len = wepKey.length; let len = wepKey.length;
// WEP-40, WEP-104, and some vendors using 256-bit WEP (WEP-232?) // WEP-40, WEP-104, and some vendors using 256-bit WEP (WEP-232?)
...@@ -99,78 +69,100 @@ function isHexWepKey(wepKey:string):boolean { ...@@ -99,78 +69,100 @@ function isHexWepKey(wepKey:string):boolean {
return isHex(wepKey); return isHex(wepKey);
} }
/**
* android 平台特有的Wifi信息对象,主要是加了加密信息这个字段
*/
export type AndroidUniWifiInfo = {
SSID : string;
BSSID ?: string;
secure : boolean;
signalStrength : number;
frequency : number;
securityType : string;
}
function wrapUniWifiInfoFromAndroid(androidInfo : AndroidUniWifiInfo) : UniWifiInfo {
let ret : UniWifiInfo = {
SSID: androidInfo.SSID,
BSSID: androidInfo.BSSID,
secure: androidInfo.secure,
signalStrength: androidInfo.signalStrength,
frequency: androidInfo.frequency,
}
return ret
}
/** /**
* Wifi信息统一数据结构 * 从扫描结果中提取统一的wifi数据结构
*/ */
class UniWifiInfo { function wrapUniWifiInfoFromScan(scanResult : ScanResult) : AndroidUniWifiInfo {
SSID: string = ""; let ret : AndroidUniWifiInfo = {
BSSID: string = ""; SSID: "",
secure: boolean = false; secure: false,
signalStrength: Number = 0; signalStrength: 0,
frequency: Number = 0; frequency: 0,
securityType: "NONE"
/*下面的字段属于扩展字段*/ }
securityType:string = "" if (scanResult != null) {
// 如果是通过扫描列表得到的数据,进行封装
constructor(scanResult: ScanResult|null = null) { ret.BSSID = scanResult.BSSID;
if (scanResult != null) { ret.SSID = scanResult.SSID;
// 如果是通过扫描列表得到的数据,进行封装
this.BSSID = scanResult.BSSID; ret.signalStrength = scanResult.level;
this.SSID = scanResult.SSID; ret.frequency = scanResult.frequency;
this.signalStrength = scanResult.level; // 是否安全,微信的标准是是否需要密码。 来源:https://developers.weixin.qq.com/community/develop/doc/00064cf1790458db19cddf9925ac00?highLine=WifiInfo
this.frequency = scanResult.frequency; ret.secure = false;
let capabilities = scanResult.capabilities.trim();
// 是否安全,微信的标准是是否需要密码。 来源:https://developers.weixin.qq.com/community/develop/doc/00064cf1790458db19cddf9925ac00?highLine=WifiInfo if ((capabilities.equals(Global.WIFI_AUTH_OPEN) || capabilities.equals(Global.WIFI_AUTH_ROAM))) {
this.secure = false; ret.secure = false;
let capabilities = scanResult.capabilities.trim(); } else {
if ((capabilities.equals(Global.WIFI_AUTH_OPEN) || capabilities.equals(Global.WIFI_AUTH_ROAM))) { ret.secure = true;
this.secure = false;
} else {
this.secure = true;
}
/*扩展字段*/
this.securityType = getSecurityType(scanResult);
} }
/*扩展字段*/
ret.securityType = getSecurityType(scanResult);
} }
/** return ret
* 根据connectInfo 链接信息对wifi数据结构进行初始化 }
*/ /**
wrapConnectInfo(connectInfo: WifiInfo): void { * 从链接信息中提取统一的wifi数据结构
*/
if (connectInfo.getBSSID() == null) { function wrapUniWifiInfoFromConnectInfo(connectInfo : WifiInfo) : UniWifiInfo {
return let ret : UniWifiInfo = {
} SSID: "",
if (connectInfo.getSSID() != null) { secure: false,
let s = connectInfo.getSSID(); signalStrength: 0,
// 微信不带,这里需要去掉引号 frequency: 0,
if (s.length > 2 && s.charAt(0) == '"' && s.charAt(s.length - 1) == '"') { }
s = s.substring(1, s.length - 1);
}
this.SSID = s; if (connectInfo.getSSID() != null) {
let s = connectInfo.getSSID();
// 微信不带,这里需要去掉引号
if (s.length > 2 && s.charAt(0) == '"' && s.charAt(s.length - 1) == '"') {
s = s.substring(1, s.length - 1);
} }
ret.SSID = s;
this.BSSID = connectInfo.getBSSID();
//Android返回的值是-100~0,而微信API规范是0~100,值越大信号越好,需要+100拉齐
this.signalStrength = connectInfo.getRssi() + 100;
this.frequency = connectInfo.getFrequency();
} }
ret.BSSID = connectInfo.getBSSID();
//Android返回的值是-100~0,而微信API规范是0~100,值越大信号越好,需要+100拉齐
ret.signalStrength = connectInfo.getRssi() + 100;
ret.frequency = connectInfo.getFrequency();
return ret
} }
/** /**
* 连接wifi时使用,根据用户输入内容包装为系统需要的wifi配置对象 * 连接wifi时使用,根据用户输入内容包装为系统需要的wifi配置对象
*/ **/
@Suppress("DEPRECATION") @Suppress("DEPRECATION")
function wrapWifiConfiguration(SSID:string ,password:string,passwordType:string):WifiConfiguration { function wrapWifiConfiguration(SSID : string, password ?: string, passwordType : string) : WifiConfiguration {
let config = new WifiConfiguration(); let config = new WifiConfiguration();
config.status = WifiConfiguration.Status.ENABLED; config.status = WifiConfiguration.Status.ENABLED;
config.allowedAuthAlgorithms.clear(); config.allowedAuthAlgorithms.clear();
...@@ -179,15 +171,15 @@ function wrapWifiConfiguration(SSID:string ,password:string,passwordType:string) ...@@ -179,15 +171,15 @@ function wrapWifiConfiguration(SSID:string ,password:string,passwordType:string)
config.allowedPairwiseCiphers.clear(); config.allowedPairwiseCiphers.clear();
config.allowedProtocols.clear(); config.allowedProtocols.clear();
config.SSID = "\"".concat(SSID).concat("\""); config.SSID = "\"".concat(SSID).concat("\"");
// nopass // nopass
if ("NONE".equals(passwordType)) { if ("NONE".equals(passwordType) || password == null) {
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
} }
// wep // wep
if ("WEP".equals(passwordType)) { else if ("WEP".equals(passwordType)) {
if (!TextUtils.isEmpty(password)) { if (password != null && !TextUtils.isEmpty(password)) {
if (isHexWepKey(password)) { if (isHexWepKey(password)) {
config.wepKeys[0] = password; config.wepKeys[0] = password;
} else { } else {
...@@ -200,7 +192,7 @@ function wrapWifiConfiguration(SSID:string ,password:string,passwordType:string) ...@@ -200,7 +192,7 @@ function wrapWifiConfiguration(SSID:string ,password:string,passwordType:string)
config.wepTxKeyIndex = 0; config.wepTxKeyIndex = 0;
} }
// wpa // wpa
if ("WPA".equals(passwordType)) { else if ("WPA".equals(passwordType)) {
config.allowedProtocols.set(WifiConfiguration.Protocol.RSN); config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
config.allowedProtocols.set(WifiConfiguration.Protocol.WPA); config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
...@@ -212,50 +204,55 @@ function wrapWifiConfiguration(SSID:string ,password:string,passwordType:string) ...@@ -212,50 +204,55 @@ function wrapWifiConfiguration(SSID:string ,password:string,passwordType:string)
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
config.preSharedKey = "\"".concat(password).concat("\""); config.preSharedKey = "\"".concat(password).concat("\"");
} }
return config; return config;
} }
/** /**
* 判断当前wifi的加密类型 * 判断当前wifi的加密类型
*/ */
function getSecurityType(result:ScanResult):string { function getSecurityType(result : ScanResult) : string {
if (result.capabilities.contains("WEP")) { if (result.capabilities.contains("WEP")) {
return "WEP"; return "WEP";
} else if (result.capabilities.contains("PSK")) { } else if (result.capabilities.contains("PSK")) {
return "WPA"; return "WPA";
} else if (result.capabilities.contains("EAP")) { } else if (result.capabilities.contains("EAP")) {
return "EAP"; return "EAP";
} }
return "NONE"; return "NONE";
} }
function zeroCountNum(source:string):number{ function zeroCountNum(source ?: string) : number {
if (source == null) {
return 0
}
var splitted = source.split(":") var splitted = source.split(":")
var countNum = 0; var countNum = 0;
for(perItem in splitted){ for (perItem in splitted) {
if(perItem == "00"){ if (perItem == "00") {
countNum += 1 countNum += 1
} }
} }
return countNum return countNum
} }
/** /**
* 自定义wifi变化广播监听器 * 自定义wifi变化广播监听器
*/ */
@Suppress("UNUSED_PARAMETER","DEPRECATION") @Suppress("UNUSED_PARAMETER", "DEPRECATION")
class CustomBroadcastReceiver extends BroadcastReceiver { class CustomBroadcastReceiver extends BroadcastReceiver {
mWifiManager: WifiManager|null = null; mWifiManager : WifiManager | null = null;
constructor(wifiManager: WifiManager) { constructor(wifiManager : WifiManager) {
super(); super();
this.mWifiManager = wifiManager; this.mWifiManager = wifiManager;
} }
override onReceive(_context: Context, intent: Intent): void { override onReceive(_context : Context, intent : Intent) : void {
if (intent.action == WifiManager.WIFI_STATE_CHANGED_ACTION) { if (intent.action == WifiManager.WIFI_STATE_CHANGED_ACTION) {
...@@ -263,20 +260,26 @@ class CustomBroadcastReceiver extends BroadcastReceiver { ...@@ -263,20 +260,26 @@ class CustomBroadcastReceiver extends BroadcastReceiver {
intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN) intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN)
if (state == WifiManager.WIFI_STATE_ENABLED) { if (state == WifiManager.WIFI_STATE_ENABLED) {
// 获取当前的connectInfo 并且进行数据封装 // 获取当前的connectInfo 并且进行数据封装
let uniWifiInfo = new UniWifiInfo(null) // let uniWifiInfo = new UniWifiInfo(null)
let uniWifiInfo : UniWifiInfo = {
SSID: "",
secure: false,
signalStrength: 0,
frequency: 0,
}
//做一些异步操作 //做一些异步操作
setTimeout(function() { setTimeout(function () {
// BroadcastReceiver 中不能执行耗时任务,需要使用setTimeout // BroadcastReceiver 中不能执行耗时任务,需要使用setTimeout
// @ts-ignore // @ts-ignore
let winfo = this.mWifiManager!.getConnectionInfo(); let winfo = this.mWifiManager!.getConnectionInfo();
while (winfo.bssid == null || zeroCountNum(winfo.bssid) > 4) { while (winfo.bssid == null || zeroCountNum(winfo.bssid) > 4) {
Thread.sleep(1000) Thread.sleep(1000)
winfo = this.mWifiManager!.getConnectionInfo(); winfo = this.mWifiManager!.getConnectionInfo();
} }
// 封装成数据对象 // 封装成数据对象
uniWifiInfo.wrapConnectInfo(winfo) uniWifiInfo = wrapUniWifiInfoFromConnectInfo(winfo)
let res = { let res = {
errMsg: 'onWifiConnected:ok', errMsg: 'onWifiConnected:ok',
errCode: 0, errCode: 0,
...@@ -288,7 +291,7 @@ class CustomBroadcastReceiver extends BroadcastReceiver { ...@@ -288,7 +291,7 @@ class CustomBroadcastReceiver extends BroadcastReceiver {
} }
// 封装仅SSID 数据对象 // 封装仅SSID 数据对象
var connectedWithPartialInfo = { var connectedWithPartialInfo = {
SSID:uniWifiInfo.SSID SSID: uniWifiInfo.SSID
} }
for (let perCallback in Global.onWifiConnectWithPartialInfoCallbackList) { for (let perCallback in Global.onWifiConnectWithPartialInfoCallbackList) {
perCallback(connectedWithPartialInfo); perCallback(connectedWithPartialInfo);
...@@ -301,26 +304,44 @@ class CustomBroadcastReceiver extends BroadcastReceiver { ...@@ -301,26 +304,44 @@ class CustomBroadcastReceiver extends BroadcastReceiver {
if (intent.action == WifiManager.SCAN_RESULTS_AVAILABLE_ACTION) { if (intent.action == WifiManager.SCAN_RESULTS_AVAILABLE_ACTION) {
startWifiScaning = false;
let ret : UniWifiResult = {
errCode: 0,
errSubject: "uni-getWifiList",
errMsg: "getWifiList:ok"
}
if(Global.supendGetWifiSuccess != null){
Global.supendGetWifiSuccess?.(ret)
}
if(Global.supendGetWifiComplete != null){
Global.supendGetWifiComplete?.(ret)
}
// wifi 扫描结果回调 // wifi 扫描结果回调
let results = this.mWifiManager!.scanResults; let results = this.mWifiManager!.scanResults;
if (results != null) { if (results != null) {
Global.scanList = [] Global.scanList = []
for (let scanResult in results) { for (let scanResult in results) {
if (scanResult.SSID == null) { if (scanResult.SSID == null) {
continue; continue;
} }
Global.scanList.push(new UniWifiInfo(scanResult)); Global.scanList.push(wrapUniWifiInfoFromScan(scanResult));
} }
// 挨个通知,所有的监听器 // 挨个通知,所有的监听器
for (let perCallback in Global.getWifiListCallbackList) { if(Global.onGetWifiListCallback != null){
const data = new JSONObject(); const data = new JSONObject();
// let mainJsonStr = Gson().toJson(Global.scanList);
data["wifiList"] = Global.scanList data["wifiList"] = Global.scanList
perCallback(data); Global.onGetWifiListCallback?.(data);
} }
// for (let perCallback in Global.onGetWifiListCallback) {
// const data = new JSONObject();
// data["wifiList"] = Global.scanList
// perCallback(data);
// }
} }
...@@ -332,20 +353,24 @@ class CustomBroadcastReceiver extends BroadcastReceiver { ...@@ -332,20 +353,24 @@ class CustomBroadcastReceiver extends BroadcastReceiver {
/************************* 下面是对外提供的函数 *************************/ /************************* 下面是对外提供的函数 *************************/
/**
* start wifi是否正在扫描
*/
var startWifiScaning = false
/** /**
* 开启wifi * 开启wifi
*/ */
@Suppress("DEPRECATION") @Suppress("DEPRECATION")
export function startWifi(option: WifiOption) { export function startWifi(option : WifiOption) {
// 需要先开启wifi,才能使用后续的功能 // 需要先开启wifi,才能使用后续的功能
let requestCode = 1001; let requestCode = 1001;
let permissionWifi = arrayOf("android.permission.ACCESS_FINE_LOCATION"); let permissionWifi = arrayOf("android.permission.ACCESS_FINE_LOCATION");
var result = { var result : UniWifiResult = {
errCode: 12001, errCode: 12001,
errMsg: "startWifi:premission loss", errMsg: "startWifi:premission loss",
errSubject:"uni-startWifi" errSubject: "uni-startWifi"
} }
// 检查权限 // 检查权限
if (ActivityCompat.checkSelfPermission(UTSAndroid.getUniActivity()!, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.checkSelfPermission(UTSAndroid.getUniActivity()!, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
...@@ -357,24 +382,33 @@ export function startWifi(option: WifiOption) { ...@@ -357,24 +382,33 @@ export function startWifi(option: WifiOption) {
return; return;
} }
// 具备了权限,继续前进 // 具备了权限,继续前进
let wifiManager: WifiManager = let wifiManager : WifiManager =
UTSAndroid.getAppContext()!.getSystemService(Context.WIFI_SERVICE) as WifiManager UTSAndroid.getAppContext()!.getSystemService(Context.WIFI_SERVICE) as WifiManager
// 用户没有开启wifi 总开关 // 用户没有开启wifi 总开关
if(!wifiManager.isWifiEnabled()){ if (!wifiManager.isWifiEnabled()) {
// wifi 没开启 // wifi 没开启
result.errCode = 12005; result.errCode = 12005;
result.errMsg = "wifi not turned on"; result.errMsg = "wifi not turned on";
option.fail?.(result); option.fail?.(result);
option.complete?.(result); option.complete?.(result);
return; return;
} }
// 初始化wifi 状态广播监听,后续所有的api,均基于此 // 初始化wifi 状态广播监听,后续所有的api,均基于此
if (Global.mReceiver == null) { if(Global.mReceiver != null){
Global.mReceiver = new CustomBroadcastReceiver(wifiManager) // 说明已经注册过了
result.errCode = 0
result.errMsg = "startWifi:ok"
option.success?.(result)
option.complete?.(result)
return
} }
Global.mReceiver = new CustomBroadcastReceiver(wifiManager)
let filter = new IntentFilter() let filter = new IntentFilter()
filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION) filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)
...@@ -382,81 +416,81 @@ export function startWifi(option: WifiOption) { ...@@ -382,81 +416,81 @@ export function startWifi(option: WifiOption) {
filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION) filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION)
// @ts-ignore // @ts-ignore
filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION); filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
UTSAndroid.getUniActivity()!.registerReceiver(Global.mReceiver, filter) UTSAndroid.getUniActivity()!.registerReceiver(Global.mReceiver, filter)
/** /**
* activity 被销毁时,取消注册 * activity 被销毁时,取消注册
*/ */
UTSAndroid.onAppActivityDestroy(function(){ UTSAndroid.onAppActivityDestroy(function () {
if(Global.mReceiver!= null){ if (Global.mReceiver != null) {
UTSAndroid.getUniActivity()!.unregisterReceiver(Global.mReceiver) UTSAndroid.getUniActivity()!.unregisterReceiver(Global.mReceiver)
Global.mReceiver = null Global.mReceiver = null
Global.scanList = [] Global.scanList = []
Global.getWifiListCallbackList = [] Global.onGetWifiListCallback = null
Global.onWifiConnectCallbackList = [] Global.onWifiConnectCallbackList = []
Global.onWifiConnectWithPartialInfoCallbackList = [] Global.onWifiConnectWithPartialInfoCallbackList = []
} }
}); });
startWifiScaning = true
// 开始扫描 // 开始扫描
wifiManager.startScan() wifiManager.startScan()
result.errCode = 0 result.errCode = 0
result.errMsg = "startWifi:ok" result.errMsg = "startWifi:ok"
option.success?.(result) option.success?.(result)
option.complete?.(result) option.complete?.(result)
} }
/** /**
* 获取wifi列表 * 获取wifi列表
*/ */
@Suppress("DEPRECATION") @Suppress("DEPRECATION")
export function getWifiList(option: WifiOption) { export function getWifiList(option : WifiOption) {
var result = { var result : UniWifiResult = {
errCode: 12000, errCode: 12000,
errMsg: "getWifiList:fail:not invoke startWifi", errMsg: "getWifiList:fail:not invoke startWifi",
errSubject:"uni-getWifiList" errSubject: "uni-getWifiList"
} }
if (Global.mReceiver == null) { if (Global.mReceiver == null) {
// 还没调用startWifi 提示报错 // 还没调用startWifi 提示报错
option.fail?.(result) option.fail?.(result)
option.complete?.(result) option.complete?.(result)
return return
} }
let wifiManager: WifiManager = let wifiManager : WifiManager =
UTSAndroid.getAppContext()!.getSystemService(Context.WIFI_SERVICE) as WifiManager UTSAndroid.getAppContext()!.getSystemService(Context.WIFI_SERVICE) as WifiManager
Global.supendGetWifiSuccess = option.success
Global.supendGetWifiComplete = option.complete
wifiManager.startScan() wifiManager.startScan()
let ret = {
errCode: 0,
errMsg: "getWifiList:ok"
}
option.success?.(ret)
option.complete?.(ret)
} }
/** /**
* wifi 链接成功的回调注册 * wifi 链接成功的回调注册
*/ */
export function onWifiConnected(callback: UTSCallback) { export function onWifiConnected(callback : UTSCallback) {
Global.onWifiConnectCallbackList.push(callback) Global.onWifiConnectCallbackList.push(callback)
} }
export function onWifiConnectedWithPartialInfo(callback: UTSCallback) { export function onWifiConnectedWithPartialInfo(callback : UTSCallback) {
Global.onWifiConnectWithPartialInfoCallbackList.push(callback) Global.onWifiConnectWithPartialInfoCallbackList.push(callback)
} }
...@@ -464,94 +498,86 @@ export function onWifiConnectedWithPartialInfo(callback: UTSCallback) { ...@@ -464,94 +498,86 @@ export function onWifiConnectedWithPartialInfo(callback: UTSCallback) {
/** /**
* wifi 链接成功的回调取消注册 * wifi 链接成功的回调取消注册
*/ */
export function offWifiConnected(callback: UTSCallback) { export function offWifiConnected(callback? : UTSCallback) {
if(callback == null){
Global.onWifiConnectCallbackList = []
return
}
let callbackIndex = Global.onWifiConnectCallbackList.indexOf(callback) let callbackIndex = Global.onWifiConnectCallbackList.indexOf(callback)
if (callbackIndex > 0) { if (callbackIndex >= 0) {
Global.onWifiConnectCallbackList.splice(callbackIndex, 1); Global.onWifiConnectCallbackList.splice(callbackIndex, 1);
} }
} }
export function offWifiConnectedWithPartialInfo(callback: UTSCallback) { /**
* 不具备详细信息的wifi 反注册
*/
export function offWifiConnectedWithPartialInfo(callback? : UTSCallback) {
if(callback == null){
Global.onWifiConnectWithPartialInfoCallbackList = []
return
}
let callbackIndex = Global.onWifiConnectWithPartialInfoCallbackList.indexOf(callback) let callbackIndex = Global.onWifiConnectWithPartialInfoCallbackList.indexOf(callback)
if (callbackIndex > 0) { if (callbackIndex >= 0) {
Global.onWifiConnectWithPartialInfoCallbackList.splice(callbackIndex, 1); Global.onWifiConnectWithPartialInfoCallbackList.splice(callbackIndex, 1);
} }
} }
/** /**
* 注册Wifi列表的监听事件 * 注册Wifi列表的监听事件
*/ */
export function onGetWifiList(callback: UTSCallback) { export function onGetWifiList(callback : UTSCallback) {
Global.getWifiListCallbackList.push(callback) Global.onGetWifiListCallback = callback
} }
/** /**
* 取消注册Wifi列表的监听事件 * 取消注册Wifi列表的监听事件
*/ */
export function offGetWifiList(callback: UTSCallback) { export function offGetWifiList(callback? : UTSCallback) {
let callbackIndex = Global.getWifiListCallbackList.indexOf(callback) Global.onGetWifiListCallback = null
if (callbackIndex > 0) { Global.supendGetWifiComplete = null
Global.getWifiListCallbackList.splice(callbackIndex, 1); Global.supendGetWifiSuccess = null
}
} }
/** /**
* 链接指定wifi * 真正执行wifi链接逻辑
*/ */
@Suppress("UNUSED_PARAMETER","DEPRECATION") function realWifiConnect(option : WifiConnectOption,result : UniWifiResult){
export function connectWifi(option: WifiConnectOption) {
var result = {
errCode: 12000,
errMsg: "connectWifi:fail:not invoke startWifi",
errSubject:"uni-connectWifi",
}
if (Global.mReceiver == null || Global.scanList.length < 1) { if (Global.mReceiver == null || Global.scanList.length < 1) {
// 还没调用startWifi 提示报错
option.fail?.(result) option.fail?.(result)
option.complete?.(result) option.complete?.(result)
return
}
if(option.maunal == true){
// 指定了手动模式
let manunalIntent = new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS);
UTSAndroid.getUniActivity()!.startActivity(manunalIntent);
result.errCode = 0 return
result.errMsg = "connectWifi:ok"
option.success?.(result)
option.complete?.(result)
return
} }
// 执行后续的逻辑 // 执行后续的逻辑
let scanWifiInfo:UniWifiInfo|null = null let scanWifiInfo : AndroidUniWifiInfo | null = null
for (let scanResult in Global.scanList) { for (let scanResult in Global.scanList) {
if (scanResult.SSID.equals(option.SSID)) { if (scanResult.SSID.equals(option.SSID)) {
scanWifiInfo = scanResult scanWifiInfo = scanResult
} }
} }
if(scanWifiInfo == null){ if (scanWifiInfo == null) {
// 不在扫描列表中返回错误 // 不在扫描列表中返回错误
option.fail?.(result) option.fail?.(result)
option.complete?.(result) option.complete?.(result)
return return
} }
let wifiConfigration = wrapWifiConfiguration(scanWifiInfo.SSID,option.password,scanWifiInfo.securityType); let wifiConfigration = wrapWifiConfiguration(scanWifiInfo.SSID, option.password, scanWifiInfo.securityType);
wifiConfigration.BSSID = scanWifiInfo.BSSID wifiConfigration.BSSID = scanWifiInfo.BSSID
let wifiManager: WifiManager = let wifiManager : WifiManager =
UTSAndroid.getAppContext()!.getSystemService(Context.WIFI_SERVICE) as WifiManager UTSAndroid.getAppContext()!.getSystemService(Context.WIFI_SERVICE) as WifiManager
// 如果已经存在了指定wifi 配置,移除之 // 如果已经存在了指定wifi 配置,移除之
let targetExistConfig:WifiConfiguration|null = null let targetExistConfig : WifiConfiguration | null = null
let existingConfigs = wifiManager.getConfiguredNetworks(); let existingConfigs = wifiManager.getConfiguredNetworks();
for (let existingConfig in existingConfigs) { for (let existingConfig in existingConfigs) {
if (existingConfig.SSID.equals("\"" + option.SSID + "\"")) { if (existingConfig.SSID.equals("\"" + option.SSID + "\"")) {
...@@ -560,83 +586,91 @@ export function connectWifi(option: WifiConnectOption) { ...@@ -560,83 +586,91 @@ export function connectWifi(option: WifiConnectOption) {
} }
// 如果wifi已经保存了当前ssid的配置,可能是别的应用添加的。android系统要求,需要删除掉重新添加 // 如果wifi已经保存了当前ssid的配置,可能是别的应用添加的。android系统要求,需要删除掉重新添加
if (targetExistConfig != null) { if (targetExistConfig != null) {
console.log("targetExistConfig.networkId === " + targetExistConfig.networkId);
let removeRet = wifiManager.removeNetwork(targetExistConfig.networkId); let removeRet = wifiManager.removeNetwork(targetExistConfig.networkId);
if(!removeRet){ if (!removeRet) {
// 移除之前的配置失败了,返回错误,需要用户手动取消保存一下
result.errCode = 12013 // add since 2023-03-28,如果当前系统大于等于android10, 则明确当前系统不支持
result.errMsg = "connectWifi:wifi config may be expired" if(Build.VERSION.SDK_INT > 28){
// 系统大于android 9
result.errCode = 12001
result.errMsg = "connectWifi:system not support"
}else{
// 移除之前的配置失败了,返回错误,需要用户手动取消保存一下
result.errCode = 12013
result.errMsg = "connectWifi:wifi config may be expired"
}
option.fail?.(result) option.fail?.(result)
option.complete?.(result) option.complete?.(result)
return return
} }
} }
let currentConnect = wifiManager.getConnectionInfo() let currentConnect = wifiManager.getConnectionInfo()
if(currentConnect.networkId >= 0){ if (currentConnect.networkId >= 0) {
wifiManager.disableNetwork(currentConnect.networkId) wifiManager.disableNetwork(currentConnect.networkId)
}else{ } else {
wifiManager.removeNetwork(currentConnect.networkId) wifiManager.removeNetwork(currentConnect.networkId)
} }
wifiManager.disconnect() wifiManager.disconnect()
let connected = false; let connected = false;
try { try {
let netID = wifiManager.addNetwork(wifiConfigration); let netID = wifiManager.addNetwork(wifiConfigration);
// 如果-1 说明没添加上,报错即可 // 如果-1 说明没添加上,报错即可
if(netID < 0){ if (netID < 0) {
result.errCode = 12002 result.errCode = 12002
result.errMsg = "connectWifi:password error Wi-Fi" result.errMsg = "connectWifi:password error Wi-Fi"
option.fail?.(result) option.fail?.(result)
option.complete?.(result) option.complete?.(result)
return return
} }
let enabled = wifiManager.enableNetwork(netID, true); let enabled = wifiManager.enableNetwork(netID, true);
if(!enabled){ if (!enabled) {
result.errCode = 12007 result.errCode = 12007
result.errMsg = "connectWifi:user denied" result.errMsg = "connectWifi:user denied"
option.fail?.(result) option.fail?.(result)
option.complete?.(result) option.complete?.(result)
return return
} }
connected = wifiManager.reconnect(); connected = wifiManager.reconnect();
} catch (e) { } catch (e) {
connected = false; connected = false;
console.log(e); console.log(e);
} }
if(!connected){ if (!connected) {
// 出错了,返回错误 // 出错了,返回错误
// 兜底的报错 // 兜底的报错
result.errCode = 12010 result.errCode = 12010
result.errMsg = "connectWifi:fail:unknown error" result.errMsg = "connectWifi:fail:unknown error"
option.fail?.(result) option.fail?.(result)
option.complete?.(result) option.complete?.(result)
return return
} }
wifiManager.saveConfiguration() wifiManager.saveConfiguration()
//scanWifiInfo 根据 partialInfo 填充给返回字段 //scanWifiInfo 根据 partialInfo 填充给返回字段
if(option.partialInfo){ if (option.partialInfo != null && option.partialInfo == true) {
result['wifi'] = { let wifiPartialInfo : UniWifiInfo = {
SSID:scanWifiInfo.SSID SSID: scanWifiInfo.SSID
} }
}else{ result.wifi = wifiPartialInfo
result['wifi'] = scanWifiInfo } else {
result.wifi = wrapUniWifiInfoFromAndroid(scanWifiInfo)
} }
// result.wifi = scanWifiInfo.toUTSJSON(option.partialInfo) // result.wifi = scanWifiInfo.toUTSJSON(option.partialInfo)
...@@ -645,19 +679,71 @@ export function connectWifi(option: WifiConnectOption) { ...@@ -645,19 +679,71 @@ export function connectWifi(option: WifiConnectOption) {
option.success?.(result) option.success?.(result)
option.complete?.(result) option.complete?.(result)
}
/**
* 链接指定wifi
*/
@Suppress("UNUSED_PARAMETER", "DEPRECATION")
export function connectWifi(option : WifiConnectOption) {
var result : UniWifiResult = {
errCode: 12000,
errMsg: "connectWifi:fail:not invoke startWifi",
errSubject: "uni-connectWifi",
}
if (option.maunal == true) {
// 指定了手动模式
let manunalIntent = new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS);
UTSAndroid.getUniActivity()!.startActivity(manunalIntent);
result.errCode = 0
result.errMsg = "connectWifi:ok"
option.success?.(result)
option.complete?.(result)
return
}
// add since 2022-03-28 ,增加逻辑,如果正在扫描中,则可以等待5s
if(startWifiScaning){
let taskCount = 0
let taskId:number = 0
taskId = setInterval(function(){
taskCount += 1;
if(taskCount >= 5 || startWifiScaning == false){
// 超过10s了。或者扫描过程结束了
clearInterval(taskId)
realWifiConnect(option,result)
}
},2000)
UTSAndroid.onAppActivityDestroy(function () {
clearInterval(taskId)
});
}else{
realWifiConnect(option,result)
}
} }
/** /**
* 关闭wifi * 关闭wifi
*/ */
export function stopWifi(option: WifiOption) { export function stopWifi(option : WifiOption) {
// 需要先开启wifi,才能使用后续的功能 // 需要先开启wifi,才能使用后续的功能
if (Global.mReceiver == null) { if (Global.mReceiver == null) {
var result = { var result : UniWifiResult = {
errNo: 12000,
errCode: 12000, errCode: 12000,
errSubject: "uni-stopWifi",
errMsg: "stopWifi:not init" errMsg: "stopWifi:not init"
} }
option.fail?.(result) option.fail?.(result)
...@@ -665,16 +751,21 @@ export function stopWifi(option: WifiOption) { ...@@ -665,16 +751,21 @@ export function stopWifi(option: WifiOption) {
return return
} }
try{ try {
UTSAndroid.getUniActivity()!.unregisterReceiver(Global.mReceiver) UTSAndroid.getUniActivity()!.unregisterReceiver(Global.mReceiver)
}catch(e){ } catch (e) {
// 多次调用 // 多次调用
//TODO handle the exception //TODO handle the exception
} }
var result = { Global.onGetWifiListCallback = null
errNo: 0, Global.onWifiConnectWithPartialInfoCallbackList = []
Global.onWifiConnectCallbackList = []
Global.mReceiver = null
let result : UniWifiResult = {
errCode: 0, errCode: 0,
errSubject: "uni-stopWifi",
errMsg: "stopWifi:ok" errMsg: "stopWifi:ok"
} }
option.success?.(result) option.success?.(result)
...@@ -686,36 +777,37 @@ export function stopWifi(option: WifiOption) { ...@@ -686,36 +777,37 @@ export function stopWifi(option: WifiOption) {
* 获取当前连接中的wifi信息 * 获取当前连接中的wifi信息
*/ */
@Suppress("DEPRECATION") @Suppress("DEPRECATION")
export function getConnectedWifi(option: GetConnectedWifiOptions) { export function getConnectedWifi(option : GetConnectedWifiOptions) {
let wifiInfo = new UniWifiInfo(null) let wifiInfo : UniWifiInfo = {
SSID: ""
}
var res = { var res : UniWifiResult = {
errCode: 12000, errCode: 12000,
errMsg: "getConnectedWifi:fail:not invoke startWifi", errMsg: "getConnectedWifi:fail:not invoke startWifi",
errSubject:"uni-getConnectedWifi", errSubject: "uni-getConnectedWifi",
} }
if (Global.mReceiver == null) { if (Global.mReceiver == null) {
// 还没调用startWifi 提示报错 // 还没调用startWifi 提示报错
option.fail?.(res) option.fail?.(res)
option.complete?.(res) option.complete?.(res)
return return
} }
// 需要先校验权限,没有位置权限无法获取wifi
if (ActivityCompat.checkSelfPermission(UTSAndroid.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.errCode = 12001
res.errMsg = "getConnectedWifi:permission loss" res.errMsg = "getConnectedWifi:permission loss"
option.fail?.(res) option.fail?.(res)
option.complete?.(res) option.complete?.(res)
return; return;
} }
// TODO 应该try catch一下,把系统的错误码给返回来,然后和微信的错误码拉齐
// 需要先校验权限,没有位置权限无法获取wifi
const context = UTSAndroid.getAppContext(); const context = UTSAndroid.getAppContext();
if (context != null) { if (context != null) {
const wm = context.getSystemService( const wm = context.getSystemService(
...@@ -724,31 +816,29 @@ export function getConnectedWifi(option: GetConnectedWifiOptions) { ...@@ -724,31 +816,29 @@ export function getConnectedWifi(option: GetConnectedWifiOptions) {
// 测试android 12上可以使用 // 测试android 12上可以使用
//@ts-ignore //@ts-ignore
const winfo = wm.getConnectionInfo(); const winfo = wm.getConnectionInfo();
wifiInfo = wrapUniWifiInfoFromConnectInfo(winfo);
console.log("option.partialInfo === " + option.partialInfo);
wifiInfo.wrapConnectInfo(winfo);
// 判断一下是否wifi 关闭了 // 判断一下是否wifi 关闭了
if(option.partialInfo!){ if (option.partialInfo != null && option.partialInfo == true) {
let ret = { let ret : UniWifiInfo = {
SSID : wifiInfo.SSID SSID: wifiInfo.SSID
} }
res['wifi'] = ret; res.wifi = ret;
}else{ } else {
if(wifiInfo.BSSID == null || zeroCountNum(wifiInfo.BSSID) > 3){ if (wifiInfo.BSSID == null || zeroCountNum(wifiInfo.BSSID) > 3) {
res.errCode = 12005 res.errCode = 12005
res.errMsg = "getConnectedWifi:fail:wifi is disable" res.errMsg = "getConnectedWifi:fail:wifi is disable"
option.fail?.(res) option.fail?.(res)
option.complete?.(res) option.complete?.(res)
return return
} }
res['wifi'] = wifiInfo; res.wifi = wifiInfo;
} }
res.errCode = 0 res.errCode = 0
res.errMsg = "getConnectedWifi:ok" res.errMsg = "getConnectedWifi:ok"
option.success?.(res) option.success?.(res)
option.complete?.(res) option.complete?.(res)
return return
......
...@@ -3,60 +3,7 @@ import { CaptiveNetwork, kCNNetworkInfoKeySSID, kCNNetworkInfoKeyBSSID } from 'S ...@@ -3,60 +3,7 @@ import { CaptiveNetwork, kCNNetworkInfoKeySSID, kCNNetworkInfoKeyBSSID } from 'S
import { NSArray, NSDictionary } from 'Foundation'; import { NSArray, NSDictionary } from 'Foundation';
import { CFString } from 'CoreFoundation'; import { CFString } from 'CoreFoundation';
import { UIDevice } from 'UIKit'; import { UIDevice } from 'UIKit';
import { WifiOption, WifiConnectOption, GetConnectedWifiOptions, UniWifiInfo, UniWifiResult, UniWifiCallback, StartWifi, StopWifi, GetWifiList, OnGetWifiList, OffGetWifiList, GetConnectedWifi, ConnectWifi, OnWifiConnected, OnWifiConnectedWithPartialInfo, OffWifiConnected, OnOffWifiConnectedWithPartialInfo, SetWifiList } from "../interface.uts"
/**
* Wifi 函数通用入参封装
*/
type WifiOption = {
success?: (res: UniWifiResult) => void;
fail?: (res: UniWifiResult) => void;
complete?: (res: UniWifiResult) => void;
};
/**
* Wifi 链接参数封装
*/
type WifiConnectOption = {
SSID?: string;
BSSID?: string;
password?: string;
maunal?: boolean;
partialInfo?: boolean; //ios不生效
success?: (res: UniWifiResult) => void;
fail?: (res: UniWifiResult) => void;
complete?: (res: UniWifiResult) => void;
}
/**
* 获取当前链接的wifi信息
*/
type GetConnectedWifiOptions = {
partialInfo?: boolean
success?: (res: UniWifiResult) => void
fail?: (res: UniWifiResult) => void
complete?: (res: UniWifiResult) => void
}
/*
* 对外暴露的wifi信息
*/
type UniWifiInfo = {
SSID: string;
BSSID: string;
secure: boolean;
signalStrength: number;
frequency: number;
}
type UniWifiResult = {
errCode : number,
errSubject : string,
errMsg : string,
wifi: UniWifiInfo | null
}
type UniWifiCallback = () => void
/* /*
* 系统定位权限获取类 * 系统定位权限获取类
...@@ -135,7 +82,7 @@ function fetchConnectedWifiWithLocationPromise(option: GetConnectedWifiOptions) ...@@ -135,7 +82,7 @@ function fetchConnectedWifiWithLocationPromise(option: GetConnectedWifiOptions)
let list = arr! as NSArray let list = arr! as NSArray
let index = 0 let index = 0
while (index < list.count) { while (index < list.count) {
let item = list[index] let item = list[index]
let interfaceName = item as string let interfaceName = item as string
let dic = CNCopyCurrentNetworkInfo(interfaceName as CFString) let dic = CNCopyCurrentNetworkInfo(interfaceName as CFString)
if (dic != null) { if (dic != null) {
...@@ -157,7 +104,7 @@ function fetchConnectedWifiWithLocationPromise(option: GetConnectedWifiOptions) ...@@ -157,7 +104,7 @@ function fetchConnectedWifiWithLocationPromise(option: GetConnectedWifiOptions)
index++ index++
} }
if (wifiInfo.BSSID.length > 0 && wifiInfo.SSID.length > 0) { if (wifiInfo.BSSID!.length > 0 && wifiInfo.SSID.length > 0) {
let res: UniWifiResult = { let res: UniWifiResult = {
errSubject: "uni-getConnectedWifi", errSubject: "uni-getConnectedWifi",
errCode: 0, errCode: 0,
...@@ -204,7 +151,7 @@ class UniWiFiModuleGloabInfo { ...@@ -204,7 +151,7 @@ class UniWiFiModuleGloabInfo {
/* /*
* 初始化wifi模块 * 初始化wifi模块
*/ */
export function startWifi(option: WifiOption) { export const startWifi: StartWifi = function (option: WifiOption) {
UniWiFiModuleGloabInfo.alreadyStartWifi = true UniWiFiModuleGloabInfo.alreadyStartWifi = true
let res: UniWifiResult = { let res: UniWifiResult = {
errSubject: "uni-startWifi", errSubject: "uni-startWifi",
...@@ -219,7 +166,7 @@ export function startWifi(option: WifiOption) { ...@@ -219,7 +166,7 @@ export function startWifi(option: WifiOption) {
/* /*
* 停止wifi模块 * 停止wifi模块
*/ */
export function stopWifi(option: WifiOption) { export const stopWifi: StopWifi = function (option: WifiOption) {
UniWiFiModuleGloabInfo.alreadyStartWifi = false UniWiFiModuleGloabInfo.alreadyStartWifi = false
LocationPromiseService.promiseCompletionHandler = [] LocationPromiseService.promiseCompletionHandler = []
let res: UniWifiResult = { let res: UniWifiResult = {
...@@ -235,7 +182,7 @@ export function stopWifi(option: WifiOption) { ...@@ -235,7 +182,7 @@ export function stopWifi(option: WifiOption) {
/* /*
* 获取wifi列表, 在调用之前需要引导用户跳转到系统设置-WIFI设置页面,系统搜索周边wifi后app才能接收到回调 * 获取wifi列表, 在调用之前需要引导用户跳转到系统设置-WIFI设置页面,系统搜索周边wifi后app才能接收到回调
*/ */
export function getWifiList(option: WifiOption) { export const getWifiList: GetWifiList = function (option: WifiOption) {
let res: UniWifiResult = { let res: UniWifiResult = {
errSubject: "uni-getWifiList", errSubject: "uni-getWifiList",
errCode: 12001, errCode: 12001,
...@@ -249,14 +196,14 @@ export function getWifiList(option: WifiOption) { ...@@ -249,14 +196,14 @@ export function getWifiList(option: WifiOption) {
/* 获取wifi列表的回调 /* 获取wifi列表的回调
* note: 请在getWifiList方法的回调里调用该方法 * note: 请在getWifiList方法的回调里调用该方法
*/ */
export function onGetWifiList(callback: UniWifiCallback) { export const onGetWifiList: OnGetWifiList = function (callback: UniWifiCallback) {
} }
/* /*
* 注销获取wifi列表的回调 * 注销获取wifi列表的回调
*/ */
export function offGetWifiList(callback: UniWifiCallback) { export const offGetWifiList: OffGetWifiList = function (callback: UniWifiCallback) {
} }
...@@ -264,7 +211,7 @@ export function offGetWifiList(callback: UniWifiCallback) { ...@@ -264,7 +211,7 @@ export function offGetWifiList(callback: UniWifiCallback) {
/* /*
* 获取当前连接的wifi信息 * 获取当前连接的wifi信息
*/ */
export function getConnectedWifi(option: GetConnectedWifiOptions) { export const getConnectedWifi: GetConnectedWifi = function (option: GetConnectedWifiOptions) {
if (UniWiFiModuleGloabInfo.alreadyStartWifi == false) { if (UniWiFiModuleGloabInfo.alreadyStartWifi == false) {
let res: UniWifiResult = { let res: UniWifiResult = {
errSubject: "uni-getConnectedWifi", errSubject: "uni-getConnectedWifi",
...@@ -299,7 +246,7 @@ export function getConnectedWifi(option: GetConnectedWifiOptions) { ...@@ -299,7 +246,7 @@ export function getConnectedWifi(option: GetConnectedWifiOptions) {
/* /*
* 连接wifi * 连接wifi
*/ */
export function connectWifi(option: WifiConnectOption) { export const connectWifi: ConnectWifi = function (option: WifiConnectOption) {
let res: UniWifiResult = { let res: UniWifiResult = {
errSubject: "uni-connectWifi", errSubject: "uni-connectWifi",
errCode: 12001, errCode: 12001,
...@@ -314,35 +261,35 @@ export function connectWifi(option: WifiConnectOption) { ...@@ -314,35 +261,35 @@ export function connectWifi(option: WifiConnectOption) {
/* /*
* 连上wifi事件的监听函数 * 连上wifi事件的监听函数
*/ */
export function onWifiConnected(callback: UniWifiCallback) { export const onWifiConnected: OnWifiConnected = function (callback: UniWifiCallback) {
} }
/* /*
* 连上wifi事件的监听函数, wifiInfo仅包含ssid * 连上wifi事件的监听函数, wifiInfo仅包含ssid
*/ */
export function onWifiConnectedWithPartialInfo(callback: UniWifiCallback) { export const onWifiConnectedWithPartialInfo: OnWifiConnectedWithPartialInfo = function (callback: UniWifiCallback) {
} }
/* /*
* 移除连接上wifi的事件的监听函数,不传此参数则移除所有监听函数。 * 移除连接上wifi的事件的监听函数,不传此参数则移除所有监听函数。
*/ */
export function offWifiConnected(callback: UniWifiCallback | null) { export const offWifiConnected: OffWifiConnected = function (callback: UniWifiCallback | null) {
} }
/* /*
* 移除连接上wifi的事件的监听函数,不传此参数则移除所有监听函数。 * 移除连接上wifi的事件的监听函数,不传此参数则移除所有监听函数。
*/ */
export function onOffWifiConnectedWithPartialInfo(callback: UniWifiCallback | null) { export const onOffWifiConnectedWithPartialInfo: OnOffWifiConnectedWithPartialInfo = function (callback: UniWifiCallback | null) {
} }
/* /*
* 设置 wifiList 中 AP 的相关信息。在 onGetWifiList 回调后调用,iOS特有接口。 * 设置 wifiList 中 AP 的相关信息。在 onGetWifiList 回调后调用,iOS特有接口。
*/ */
export function setWifiList(option: WifiOption) { export const setWifiList: SetWifiList = function (option: WifiOption) {
let res: UniWifiResult = { let res: UniWifiResult = {
errSubject: "uni-setWifiList", errSubject: "uni-setWifiList",
errCode: 12001, errCode: 12001,
......
/**
* Wifi 函数通用入参封装
*/
export type WifiOption = {
success?: (res: UniWifiResult) => void;
fail?: (res: UniWifiResult) => void;
complete?: (res: UniWifiResult) => void;
};
/**
* Wifi 链接参数封装
*/
export type WifiConnectOption = {
SSID?: string;
BSSID?: string;
password?: string;
maunal?: boolean;
partialInfo?: boolean; //ios不生效
success?: (res: UniWifiResult) => void;
fail?: (res: UniWifiResult) => void;
complete?: (res: UniWifiResult) => void;
}
/**
* 获取当前链接的wifi信息
*/
export type GetConnectedWifiOptions = {
partialInfo?: boolean
success?: (res: UniWifiResult) => void
fail?: (res: UniWifiResult) => void
complete?: (res: UniWifiResult) => void
}
/*
* 对外暴露的wifi信息
*/
export type UniWifiInfo = {
SSID: string;
BSSID?: string;
secure?: boolean;
signalStrength?: number;
frequency?: number;
}
export type UniWifiResult = {
errCode : number,
errSubject : string,
errMsg : string,
wifi: UniWifiInfo | null
}
export type UniWifiCallback = () => void
export type StartWifi = (option: WifiOption) => void
export type StopWifi = (option: WifiOption) => void
export type GetWifiList = (option: WifiOption) => void
export type OnGetWifiList = (callback: UniWifiCallback) => void
export type OffGetWifiList = (callback: UniWifiCallback) => void
export type GetConnectedWifi = (option: GetConnectedWifiOptions) => void
export type ConnectWifi = (option: WifiConnectOption) => void
export type OnWifiConnected = (callback: UniWifiCallback) => void
export type OnWifiConnectedWithPartialInfo = (callback: UniWifiCallback) => void
export type OffWifiConnected = (callback: UniWifiCallback | null) => void
export type OnOffWifiConnectedWithPartialInfo = (callback: UniWifiCallback | null) => void
export type SetWifiList = (option: WifiOption) => void
interface Uni {
startWifi : StartWifi,
stopWifi : StopWifi,
/**
* @autotest {
generated: false,
pollution: false,
cases:[
{
before: 'startWifi',
after: 'stopWifi',
input: [{
maunal:false,
SSID:"Xiaomi_20D0",
password:"streamApp!2016",
}],
output:{
callbackType: 'success',
value: { errCode: 12013 ,errMsg: "connectWifi:wifi config may be expired",errSubject: "uni-connectWifi"}
}
}
]
}
*/
connectWifi: ConnectWifi,
/**
* @autotest {
generated: false,
cases:[
{
before: 'startWifi',
after: 'stopWifi'
}
]
}
*/
getWifiList : GetWifiList,
onGetWifiList : OnGetWifiList,
offGetWifiList : OffGetWifiList,
getConnectedWifi : GetConnectedWifi,
onWifiConnected : OnWifiConnected,
onWifiConnectedWithPartialInfo : OnWifiConnectedWithPartialInfo,
offWifiConnected : OffWifiConnected,
onOffWifiConnectedWithPartialInfo : OnOffWifiConnectedWithPartialInfo,
setWifiList : SetWifiList,
}
function startWifi() {
return new Promise((resolve, reject) => {
uni.startWifi({
success: () => {
console.log('startWifi success');
resolve()
},
fail: () => {
console.log('startWifi fail');
reject()
}
})
})
}
function stopWifi() {
return new Promise((resolve, reject) => {
uni.stopWifi({
success: () => {
console.log('stopWifi success');
resolve()
},
fail: () => {
console.log('stopWifi success');
fail()
}
})
})
}
module.exports = {
startWifi,
stopWifi
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册