Uts 蓝牙连接(1)
2024-06-19 本文已影响0人
空腹无才
一、准备工作
AndroidManifest.xml 中添加以下权限
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"
package="包名"
>
<!-- 蓝牙权限 -->
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<!-- 安卓12开始需要下列权限compileSDK 32+ -->
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission android:name="android.permission.ADVERTISE" />
<!-- 安卓6.0 需要定位权限 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.hardware.bluetooth_le" />
</manifest>
权限申请
import Manifest from "android.Manifest";
// 申请权限列表
let permissionNeed = [ Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.BLUETOOTH_CONNECT,
Manifest.permission.BLUETOOTH_SCAN]
// 请求权限
UTSAndroid.requestSystemPermission(UTSAndroid.getUniActivity()!, permissionNeed, function (allRight : boolean, _ : string[]) {
if (allRight) {
// 权限请求成功
} else {
//用户拒绝了部分权限
}
},function(_ : boolean, _ : string[]) {
//用户拒绝了部分权限
})catch(e) {
// 请求权限失败
}
二、蓝牙连接
获取设备蓝牙适配器
import BluetoothAdapter from "android.bluetooth.BluetoothAdapter";
this.bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(this.bluetoothAdapter == null) {
// 当前设备不支持蓝牙
}
获取蓝牙状态并启动
if(this.bluetoothAdapter as BluetoothAdapter).isEnabled() == true) {
// 蓝牙可用
try{
const enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); // 在一个对话框中开启蓝牙
UTSAndroid.getUniActivity()!.startActivity(enableBtIntent);
}catch(e){
console.log(e)
}
} else {
// 蓝牙设备未打开。。。
}
开启蓝牙搜索
(this.bluetoothAdapter as BluetoothAdapter).startDiscovery();
监听搜索信息
import BluetoothDevice from "android.bluetooth.BluetoothDevice";
import BroadcastReceiver from "android.content.BroadcastReceiver";
type callbackType = (objs: callbackParams) => void
// 接收器
const receiver = null;
if(receiver !== null) {
// 注销接收器
UTSAndroid.getUniActivity()?.unregisterReceiver(receiver);
receiver = null;
}
// 创建 注册 接收器
receiver = new Receiver(callback as callbackType)
var filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
UTSAndroid.getUniActivity()?.registerReceiver(receiver, filter)
class Receiver extends BroadcastReceiver {
private callback: callbackType | null = null;
constructor(callback: callbackType) {
super();
this.callback = callback;
}
override onReceive(context: Context, intent: Intent) {
if(intent.action == "android.bluetooth.device.action.FOUND") {
const device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE);
if(this.callback !== null) {
// console.log((device as BluetoothDevice).getAddress());
(this.callback as callbackType)({
name: (device as BluetoothDevice).getName() == null ? "" : (device as BluetoothDevice).getName(),
address: (device as BluetoothDevice).getAddress()
} as callbackParams);
}
}
}
}
关闭蓝牙搜索
if((this.bluetoothAdapter as BluetoothAdapter).isDiscovering() == true) {
(this.bluetoothAdapter as BluetoothAdapter).cancelDiscovery();
console.log("蓝牙搜索功关闭成功")
}
三、完整案例
请求权限 permissionRequest.uts
import Manifest from "android.Manifest";
type requestType = {
state: boolean,
msg: string
}
// 请求权限
export function requestPermissions():Promise<requestType> {
let permissionNeed = [ Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.BLUETOOTH_CONNECT,
Manifest.permission.BLUETOOTH_SCAN]
return new Promise((resolv) => {
try{
// 请求权限
UTSAndroid.requestSystemPermission(UTSAndroid.getUniActivity()!, permissionNeed, function (allRight : boolean, _ : string[]{
if (allRight) {
// 权限请求成功
resolv({
state: true,
msg: "权限申请成功"
} as requestType);
} else {
//用户拒绝了部分权限
resolv({
state: false,
msg: "用户拒绝了部分权限"
} as requestType);
}
}, function (_ : boolean, _ : string[]) {
//用户拒绝了部分权限
resolv({
state: false,
msg: "用户拒绝了部分权限"
} as requestType);
})
}catch(e){
resolv({
state: false,
msg: e.toString()
} as requestType);
}
})
}
蓝牙搜索 bluetoothManager.uts
import BluetoothAdapter from "android.bluetooth.BluetoothAdapter";
import BluetoothDevice from "android.bluetooth.BluetoothDevice";
import BroadcastReceiver from "android.content.BroadcastReceiver";
import Intent from "android.content.Intent";
import Context from "android.content.Context";
import IntentFilter from "android.content.IntentFilter"
import { requestPermissions } from "./permissionRequest";
type requestType = {
state: boolean,
msg: string
}
export class BluetoothManager {
// 蓝牙适配器
private bluetoothAdapter :BluetoothAdapter | null;
// 蓝牙设备获取回调函数
private callback: callbackType | null = null;
// 回调函数监听对象
private receiver: BroadcastReceiver | null = null;
constructor() {
this.bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
}
// 启动蓝牙
async ensureBluetoothSupported():Promise<requestType> {
const _r = await requestPermissions();
if(_r.state == false) {
return {
state: false,
msg: _r.msg
} as requestType;
}
if(this.bluetoothAdapter == null) {
return {
state: false,
msg: "此设备不支持蓝牙"
} as requestType;
}
const _result = this.enableBluetoothIfNeeded();
return _result;
}
// 获取蓝牙状态并启动
enableBluetoothIfNeeded():requestType {
if((this.bluetoothAdapter as BluetoothAdapter).isEnabled() == true) {
try{
const enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); // 在一个对话框中开启蓝牙
UTSAndroid.getUniActivity()!.startActivity(enableBtIntent);
}catch(e){
//TODO handle the exception
}
return {
state: true,
msg: "蓝牙运行正常"
} as requestType;
} else {
return {
state: false,
msg: "蓝牙设备未打开。。。"
}as requestType;
}
}
// 开始蓝牙设备发现
startDiscovery() {
this.stopBluetoothDiscovery();
(this.bluetoothAdapter as BluetoothAdapter).startDiscovery();
this.setupDiscoveryReceiver();
}
// 设置接收发现蓝牙设备的广播接收器
private setupDiscoveryReceiver() {
if(this.receiver !== null) {
// 注销监听
UTSAndroid.getUniActivity()?.unregisterReceiver(this.receiver);
this.receiver = null;
}
// 创建 注册监听
this.receiver = new Receiver(this.callback as callbackType)
var filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
UTSAndroid.getUniActivity()?.registerReceiver(this.receiver, filter)
}
// 关闭蓝牙搜索
stopBluetoothDiscovery() {
if((this.bluetoothAdapter as BluetoothAdapter).isDiscovering() == true) {
(this.bluetoothAdapter as BluetoothAdapter).cancelDiscovery();
console.log("蓝牙搜索功关闭成功")
}
}
// 关闭蓝牙
disableBluetooth() {
if((this.bluetoothAdapter as BluetoothAdapter).isEnabled() == true) {
(this.bluetoothAdapter as BluetoothAdapter).disable();
this.bluetoothAdapter = null;
console.log("蓝牙适配器销毁")
}
}
// 添加蓝牙搜索回调函数
addReceiver(callback: callbackType) {
this.callback = callback;
}
}
class Receiver extends BroadcastReceiver {
private callback: callbackType | null = null;
constructor(callback: callbackType) {
super();
this.callback = callback;
}
override onReceive(context: Context, intent: Intent) {
if(intent.action == "android.bluetooth.device.action.FOUND") {
const device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE);
if(this.callback !== null) {
console.log((device as BluetoothDevice).getAddress());
(this.callback as callbackType)({
name: (device as BluetoothDevice).getName() == null ? "" : (device as BluetoothDevice).getName(),
address: (device as BluetoothDevice).getAddress()
} as callbackParams);
}
}
}
}
调用 index.uts
import {BluetoothManager} from "../../uni_modules/ble-search";
bluetoothManager = new BluetoothManager();
// 启动蓝牙
const _result = await bluetoothManager.ensureBluetoothSupported();
if(_result.state) return;
// 添加回调函数
bluetoothManager.addReceiver(addBlueInfo);
// 开启蓝牙搜索功能
bluetoothManager.startDiscovery();
searchTime = setTimeout(() => {
// 关闭蓝牙搜索功能
bluetoothManager.stopBluetoothDiscovery();
}, 1000 * 10)
function addBlueInfo(data) {
bleList.value[data.address] = data;
}