美文网首页
Uts 蓝牙连接(1)

Uts 蓝牙连接(1)

作者: 空腹无才 | 来源:发表于2024-06-19 12:29 被阅读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;
}

Uts 蓝牙连接(2)

相关文章

  • 微信程序——蓝牙功能实现

    一.实现的流程图 (1)找到蓝牙 (2)连接蓝牙

  • 蓝牙连接

    蓝牙门控使用须知 1、连接蓝牙必须打开手机蓝牙和定位服务,在设备蓝牙范围内进行配对。 2、初次连接初始密码(000...

  • Android蓝牙权限

    1. 蓝牙权限 蓝牙连接和通讯需要获取相关的蓝牙权限BLUETOOTH和BLUETOOTH_ADMIN。 蓝牙权限...

  • 蓝牙设备连接----eg:蓝牙打印----(蓝牙连接设备)

    蓝牙实现打印实现 蓝牙连接外设,通过系统框架实现,步骤如下:判断是否打开蓝牙——> 搜索蓝牙设备——>连接蓝牙设备...

  • Android BLE蓝牙连接

    BLE蓝牙连接和经典蓝牙有所区别,BLE的整个连接流程为: 1,扫描设备,获取设备MAC地址 2,发起连接请求 3...

  • Android 蓝牙连接

    最近因为公司的需求,要开发蓝牙的智能设备,通过网上查找资料,终于实现了蓝牙连接,通信的功能。 重点1:蓝牙连接其实...

  • 无法连接设备以及已经连接无法识别到设备的

    一、蓝牙灯一秒一闪或者已经连接 必须两边的蓝牙都忽略才有效! 1.点开蓝牙连接列表,点击已连接设备后面的下拉框或者...

  • 安卓学习笔记1

    安卓蓝牙2.0 程序可以兼容 蓝牙4.0蓝牙 1.首先连接蓝牙 通过以下的代码: 这里面是找到蓝牙设备的代码 找到...

  • Android 经典蓝牙开发(二)

    本文章经典蓝牙开发目录: 1、权限申请2、开启蓝牙3、扫描蓝牙4、配对蓝牙5、连接蓝牙6、通信(实现双向通信)(我...

  • 微信小程序蓝牙自动连接

    小程序 蓝牙自动连接 1 初始化手机蓝牙 . 初始化成后添加 监听蓝牙是否会异常断开,监听蓝牙因为距离,手机蓝牙关...

网友评论

      本文标题:Uts 蓝牙连接(1)

      本文链接:https://www.haomeiwen.com/subject/lamqcjtx.html