提交 12e0c48c 编写于 作者: 杜庆泉's avatar 杜庆泉

修复了uts wifi 退出activity 监听器未销毁的bug

上级 409284d3
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 = {
......
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,6 +12,7 @@ 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';
......@@ -26,6 +27,8 @@ type WifiOption = {
complete?: (res: object) => void;
};
/**
* Wifi 链接参数封装
*/
......@@ -38,11 +41,11 @@ 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);
......@@ -69,6 +72,7 @@ function isHexWepKey(wepKey:string):boolean {
return isHex(wepKey);
}
@Suppress("DEPRECATION")
function wrapWifiConfiguration(SSID:string ,password:string,passwordType:string):WifiConfiguration {
let config = new WifiConfiguration();
......@@ -201,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[] = []
}
......@@ -224,6 +229,7 @@ function getSecurityType(result:ScanResult):string {
/**
* 自定义wifi变化广播监听器
*/
@Suppress("UNUSED_PARAMETER","DEPRECATION")
class CustomBroadcastReceiver extends BroadcastReceiver {
mWifiManager?: WifiManager = null;
......@@ -307,6 +313,7 @@ class CustomBroadcastReceiver extends BroadcastReceiver {
/**
* 获取wifi列表
*/
@Suppress("DEPRECATION")
export function getWifiList(option: WifiOption) {
if (Global.mReceiver == null) {
......@@ -323,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 = {
......@@ -374,6 +381,7 @@ export function offGetWifiList(callback: UTSCallback) {
/**
* 链接指定wifi
*/
@Suppress("UNUSED_PARAMETER","DEPRECATION")
export function connectWifi(option: WifiConnectOption) {
......@@ -394,7 +402,7 @@ export function connectWifi(option: WifiConnectOption) {
if(option.maunal == true){
// 指定了手动模式
let manunalIntent = new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS);
getUniActivity()!!.startActivity(manunalIntent);
UTSAndroid.getUniActivity()!.startActivity(manunalIntent);
result.errCode = 0
result.errMsg = "connectWifi:ok"
......@@ -426,7 +434,7 @@ export function connectWifi(option: WifiConnectOption) {
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
......@@ -445,6 +453,7 @@ export function connectWifi(option: WifiConnectOption) {
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
......@@ -465,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)
......@@ -489,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)
......@@ -502,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"
......@@ -529,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,
......@@ -544,6 +578,7 @@ export function stopWifi(option: WifiOption) {
/**
* 获取当前连接中的wifi信息
*/
@Suppress("DEPRECATION")
export function getConnectedWifi(option: GetConnectedWifiOptions) {
let wifiInfo = new UniWifiInfo(null)
......@@ -551,6 +586,7 @@ export function getConnectedWifi(option: GetConnectedWifiOptions) {
var res = {
errCode: 12000,
errMsg: "getConnectedWifi:fail:not invoke startWifi",
errSubject:"uni-getConnectedWifi",
wifi:wifiInfo
}
......@@ -562,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"
......@@ -574,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
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册