index.uts 9.6 KB
Newer Older
1
import Context from "android.content.Context";
杜庆泉's avatar
杜庆泉 已提交
2
import { getAppContext,getUniActivity } from "io.dcloud.uts.android";
3
import WifiManager from "android.net.wifi.WifiManager";
杜庆泉's avatar
杜庆泉 已提交
4 5 6
import WifiInfo from "android.net.wifi.WifiInfo";

import ConnectivityManager from "android.net.ConnectivityManager";
杜庆泉's avatar
杜庆泉 已提交
7 8 9 10 11 12 13 14 15
import Manifest from "android.Manifest";
import PackageManager from "android.content.pm.PackageManager";
import ScanResult from "android.net.wifi.ScanResult";
import BroadcastReceiver from "android.content.BroadcastReceiver";
import ActivityCompat from "androidx.core.app.ActivityCompat";
import IntentFilter from "android.content.IntentFilter";
import Gson from "com.google.gson.Gson";
import JSONObject from "com.alibaba.fastjson.JSONObject";
import Intent from "android.content.Intent";
杜庆泉's avatar
杜庆泉 已提交
16
import Thread from "java.lang.Thread";
17

杜庆泉's avatar
杜庆泉 已提交
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
/**
 * Wifi 函数通用入参封装
 */
type WifiOption = {
	success?: (res: object) => void;
	fail?: (res: object) => void;
	complete?: (res: object) => void;
};


/**
 * Wifi信息统一数据结构
 */
class UniWifiInfo {
	
	SSID:String = "";
	BSSID:String = "";
	secure:boolean = false;
	signalStrength:Number = 0;
	frequency:Number = 0;
	
	constructor(scanResult?:ScanResult){
		if(scanResult != null){
			// 如果是通过扫描列表得到的数据,进行封装
			this.BSSID = scanResult.BSSID;
			this.SSID = scanResult.SSID;
				
			this.signalStrength = scanResult.level;
			this.frequency = scanResult.frequency;
				
			// 是否安全,微信的标准是是否需要密码。 来源:https://developers.weixin.qq.com/community/develop/doc/00064cf1790458db19cddf9925ac00?highLine=WifiInfo
			this.secure = false;
			let capabilities = scanResult.capabilities.trim();
			if (capabilities != null && (capabilities.equals(Global.WIFI_AUTH_OPEN) || capabilities.equals(Global.WIFI_AUTH_ROAM))) {
				this.secure = false;
			}else{
				this.secure = true;
			}
		}
	}
杜庆泉's avatar
杜庆泉 已提交
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
	
	/**
	 * 根据connectInfo 链接信息对wifi数据结构进行初始化
	 */
	wrapConnectInfo(connectInfo:WifiInfo):void{
		console.log(connectInfo.getSSID());
		console.log(connectInfo.getBSSID());
		if(connectInfo.getBSSID() == null){
			return 
		}
		if (connectInfo != null) {
			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);
				}
				this.SSID = s;
			}
			
			this.BSSID = connectInfo.getBSSID();
			this.signalStrength = connectInfo.getRssi()+100; //Android返回的值是-100~0,而微信API规范是0~100,值越大信号越好,需要+100拉齐
			this.frequency = connectInfo.getFrequency();
			// WifiInfo.macAddress = winfo.getMacAddress(); //注意此代码涉及隐私,首先需要配置权限,没有权限会返回"02:00:00:00:00:00";然后需要在隐私协议中声明用途。如不需要,可注释掉本行
			
		}
	}
	
	
杜庆泉's avatar
杜庆泉 已提交
87 88 89 90 91
}

/**
 * 获取当前链接的wifi信息
 */
92
type GetConnectedWifiOptions = {
杜庆泉's avatar
杜庆泉 已提交
93
	partialInfo?:boolean
94 95 96 97 98
    success?: (res: UTSJSONObject) => void
    fail?: (res: UTSJSONObject) => void
    complete?: (res: UTSJSONObject) => void
}

杜庆泉's avatar
杜庆泉 已提交
99 100 101 102 103 104 105 106 107 108 109


/**
 * 全局数据储存
 */
class Global{
	static mReceiver?:CustomBroadcastReceiver = null;
	static scanList:UniWifiInfo[] =  []
	static WIFI_AUTH_OPEN:String  = "";
	static WIFI_AUTH_ROAM:String  = "[ESS]";
	static getWifiListCallbackList:UTSCallback[] = []
杜庆泉's avatar
杜庆泉 已提交
110
	static onWifiConnectCallbackList:UTSCallback[] = []
杜庆泉's avatar
杜庆泉 已提交
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
}


/**
 * 自定义wifi变化广播监听器
 */
class CustomBroadcastReceiver extends BroadcastReceiver{
	
	mWifiManager?:WifiManager = null;

	constructor(wifiManager: WifiManager){
		super();
		this.mWifiManager = wifiManager;
	}
	
	override onReceive(context: Context, intent: Intent) :void {
		
		
杜庆泉's avatar
杜庆泉 已提交
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
		if (intent.action == WifiManager.WIFI_STATE_CHANGED_ACTION) {
			let state =
				intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN)
			if (state == WifiManager.WIFI_STATE_ENABLED) {
				// 获取当前的connectInfo 并且进行数据封装
				let uniWifiInfo = new UniWifiInfo(null)
				let winfo = this.mWifiManager!.getConnectionInfo(); 
				while(winfo.bssid == null){
					Thread.sleep(1000)
					winfo = this.mWifiManager!!.getConnectionInfo();
				}
				
				console.log(winfo)
				// 封装成数据对象
				uniWifiInfo.wrapConnectInfo(winfo)
				let res = {
				    errMsg: 'onWifiConnected:ok',
				    errCode: 0,
				    wifi: uniWifiInfo
				}
				console.log("Global.onWifiConnectCallbackList  == " + Global.onWifiConnectCallbackList.length);
				// wifi状态可用了,分发当前的链接状态给已注册的监听集合
				for(let perCallback in Global.onWifiConnectCallbackList){
					perCallback(res);
				}
			} 
		}
		
		
杜庆泉's avatar
杜庆泉 已提交
158
		if (intent.action == WifiManager.SCAN_RESULTS_AVAILABLE_ACTION) {
杜庆泉's avatar
杜庆泉 已提交
159 160
			// wifi 扫描结果回调
			let results = this.mWifiManager!.scanResults;
杜庆泉's avatar
杜庆泉 已提交
161 162 163
			
			if (results != null) {
				Global.scanList = []
杜庆泉's avatar
杜庆泉 已提交
164
				for(let scanResult in results){
杜庆泉's avatar
杜庆泉 已提交
165 166 167
					if(scanResult.SSID == null){
					    continue;
					}
杜庆泉's avatar
杜庆泉 已提交
168
					Global.scanList.push(new UniWifiInfo(scanResult));
杜庆泉's avatar
杜庆泉 已提交
169 170 171
				}
				
				// 挨个通知,所有的监听器
杜庆泉's avatar
杜庆泉 已提交
172
				for(let perCallback in Global.getWifiListCallbackList){
杜庆泉's avatar
杜庆泉 已提交
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
					
					const data = new JSONObject();
					let mainJsonStr = Gson().toJson(Global.scanList);
					data["wifiList"] = mainJsonStr
					perCallback(data);
				}
				
			}
			
		}
	}
	
}

/************************* 下面是对外提供的函数 *************************/

/**
 * 获取wifi列表
 */
export function getWifiList(option:WifiOption) { 
	let wifiManager: WifiManager =
	                getAppContext()!.getSystemService(Context.WIFI_SERVICE) as WifiManager
	wifiManager.startScan()		
		
	let ret = {
		errNo:0,
		errCode:0,
		errMsg:"getWifiList:ok"
	}
	option?.success?.(ret)
	option?.complete?.(ret)
	
}


杜庆泉's avatar
杜庆泉 已提交
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
/**
 * wifi 链接成功的回调注册
 */
export function onWifiConnected(callback: UTSCallback) { 
	Global.onWifiConnectCallbackList.push(callback)
}

/**
 * wifi 链接成功的回调取消注册
 */
export function offWifiConnected(callback: UTSCallback) { 
	let callbackIndex = Global.onWifiConnectCallbackList.indexOf(callback)
	if(callbackIndex > 0){
		Global.onWifiConnectCallbackList.splice(callbackIndex, 1);   
	}
}

杜庆泉's avatar
杜庆泉 已提交
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
/**
 * 注册Wifi列表的监听事件
 */
export function onGetWifiList(callback: UTSCallback) { 
	
	Global.getWifiListCallbackList.push(callback)
}
/**
 * 取消注册Wifi列表的监听事件
 */
export function offGetWifiList(callback: UTSCallback) { 
	let callbackIndex = Global.getWifiListCallbackList.indexOf(callback)
	if(callbackIndex > 0){
		Global.getWifiListCallbackList.splice(callbackIndex, 1);   
	}
}

/**
 * 开启wifi
 */
export function startWifi(option:WifiOption) { 
	// 需要先开启wifi,才能使用后续的功能
	let requestCode = 1001;
	let permissionWifi = arrayOf("android.permission.ACCESS_FINE_LOCATION");
	
	// 检查权限
	if (ActivityCompat.checkSelfPermission(getUniActivity()!, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED) {
		
		ActivityCompat.requestPermissions(getUniActivity()!, permissionWifi, requestCode)
		// 尚不具备权限,返回错误
		var result = {
			errNo:0,
			errCode:0,
			errMsg:"startWifi:premission loss"
		}
		option.fail?.(result)
		option.complete?.(result)
		
		return;
	} 
	
	// 具备了权限,继续前进
	let wifiManager: WifiManager =
	                getAppContext()!.getSystemService(Context.WIFI_SERVICE) as WifiManager
					
	if (Global.mReceiver == null) {
		Global.mReceiver = new CustomBroadcastReceiver(wifiManager)
	}
	
杜庆泉's avatar
杜庆泉 已提交
274 275 276 277 278
	let filter = new IntentFilter()
	filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)
	filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION)
	filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
	
杜庆泉's avatar
杜庆泉 已提交
279 280 281 282 283 284 285 286 287
	getUniActivity()!.registerReceiver(Global.mReceiver, filter)
	wifiManager.startScan()	
	var result = {
		errNo:0,
		errCode:0,
		errMsg:"startWifi:ok"
	}
	option.success?.(result)
	option.complete?.(result)
288 289 290
	
}

杜庆泉's avatar
杜庆泉 已提交
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313

/**
 * 关闭wifi
 */
export function stopWifi(option:WifiOption) {
	// 需要先开启wifi,才能使用后续的功能
	if (Global.mReceiver == null) {
		var result = {
			errNo:12000,
			errCode:12000,
			errMsg:"stopWifi:not init"
		}
		option.fail?.(result)
		option.complete?.(result)
		
		return 
	}
	
	getUniActivity()!.unregisterReceiver(Global.mReceiver)
	var result = {
		errNo:0,
		errCode:0,
		errMsg:"stopWifi:ok"
314
	}
杜庆泉's avatar
杜庆泉 已提交
315 316 317 318 319 320 321 322 323 324 325 326 327 328
	option.success?.(result)
	option.complete?.(result)
	
}

/**
 * 获取当前连接中的wifi信息
 */
export function getConnectedWifi(option: GetConnectedWifiOptions) {
	
	console.log(option);
	
	let WifiInfo = new UniWifiInfo(null)
	
329 330 331
	let res = {
	    errMsg: 'getConnectedWifi:fail. please check permission about location or enable wifi or connect wifi',
	    errCode: -1,
杜庆泉's avatar
杜庆泉 已提交
332
	    wifi: WifiInfo
333
	}
杜庆泉's avatar
杜庆泉 已提交
334 335 336 337 338 339 340 341 342
	
	
	if (ActivityCompat.checkSelfPermission(getUniActivity()!, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED) {
		// 尚不具备权限,返回错误
		option.fail?.(res)
		option.complete?.(res)
		return;
	} 
	
343 344 345 346 347 348 349
	// TODO 应该try catch一下,把系统的错误码给返回来,然后和微信的错误码拉齐
	// 需要先校验权限,没有位置权限无法获取wifi
	const context = getAppContext();
	if (context != null) {
	    const wm = context.getSystemService(
	        Context.WIFI_SERVICE
	    ) as WifiManager;
杜庆泉's avatar
杜庆泉 已提交
350 351 352 353 354 355 356 357 358 359 360
		// 测试android 12上可以使用
		const winfo = wm.getConnectionInfo(); 
		// 封装成数据对象
		WifiInfo.wrapConnectInfo(winfo);
		
		res.errCode = 0
		res.errMsg = "getConnectedWifi:ok"
		res.wifi = WifiInfo;
		option.success?.(res)
		option.complete?.(res)
		return
361
	}
杜庆泉's avatar
杜庆泉 已提交
362 363
	option.fail?.(res)
	option.complete?.(res)
364
}