1***@qq.com
1***@qq.com
  • 发布:2019-11-25 14:08
  • 更新:2021-01-13 21:01
  • 阅读:5043

获取蓝牙设备列表的名称都是空的

分类:HTML5+

不管用不用原生,获取的设备名称都是空的
我想搜索手机的蓝牙,能 否搜索到?
<template>
<view class="content">
<view class="btn">
<button :loading="loading" type="primary" @click="onSearch">搜索蓝牙</button>
<button type="info" @click="stopBluetoothDevicesDiscovery">停止搜索</button>
</view>
<view class="select-list">
<view class="title">已配对的设备</view>
<block v-for="(item, index) in selectList" :key="index">
<view class="item">
<view class="id">deviceId:{{item.deviceId}}</view>
<view class="id">名称:{{item.name}}</view>
</view>
</block>
</view>
<view class="search-list">
<view class="title">可用设备</view>
<block v-for="(item, index) in searchList" :key="index">
<view class="item">
<view class="id">deviceId:{{item.deviceId}}</view>
<view class="id">名称:{{item.name || item.localName}}</view>
<!-- <view class="id">advertisData:{{item.advertisData}}</view> -->
<view class="uni-list_item">信号强度:{{ item.RSSI }}dBm</view>
<button type="primary" @click="createBLEConnection(item)">连接</button>
</view>
</block>
</view>
</view>
</template>

<script>
export default {
data() {
return {
loading: false,
searchList: [],
selectList: [],
isStop: true
}
},
onLoad() {
// #ifdef APP-PLUS
// this.bluetooth_list()
// this.openBluetooth()
// #endif
},
methods: {
openBluetooth() {
plus.bluetooth.openBluetoothAdapter({
success: (res) => {
console.log('open success: ', JSON.stringify(res));
},
fail: (err) => {
console.log('open failed: ', JSON.stringify(err));
}
});
},
startBluetoothDiscovery() {
this.loading = true
plus.bluetooth.startBluetoothDevicesDiscovery({
success: (res) => {
console.log('start discovery success: ', JSON.stringify(res));
this.listenerDeviceFound()
},
fail: (err) => {
console.log('start discovery failed: ', JSON.stringify(err));
}
});
setTimeout(() => {
this.loading = false
this.stopBluetoothDiscovery()
}, 10000)
},
listenerDeviceFound(){
plus.bluetooth.onBluetoothDeviceFound((res) => {
var devices = res.devices;
this.getDevices()
console.log('device found: ', res);
});
},
getDevices(){
plus.bluetooth.getBluetoothDevices({
success: (e) => {
var devices = e.devices;
this.searchList = e.devices
console.log('get devices success: ', e);
},
fail: (e) => {
console.log('get devices failed: '+JSON.stringify(e));
}
});
},
createConnection(item) {
uni.showLoading({
title: '连接中...'
})
plus.bluetooth.createBLEConnection({
deviceId: item.deviceId,
success: (res) => {
console.log('create connection success: ', res);
setTimeout(() => {
this.getServices(item)
}, 100)
},
fail: (err) => {
uni.hideLoading()
console.log('create connection failed: ', err);
}
});
},
getServices(item){
plus.bluetooth.getBLEDeviceServices({
deviceId:item.deviceId,
success: (res) => {
uni.hideLoading()
var services = res.services;
console.log('get services success: ', res);
},
fail: (err) => {
uni.hideLoading()
console.log('get services failed: ', err);
}
});
},
stopBluetoothDiscovery() {
plus.bluetooth.stopBluetoothDevicesDiscovery({
success: (res) => {
console.log('stop discovery success: ', JSON.stringify(res));
},
fail: (err) => {
console.log('stop discovery failed: ', JSON.stringify(err));
}
});
},
closePlusBluetoothAdapter() {
plus.bluetooth.closeBluetoothAdapter({
success: (res2) => {
console.log('close success: ', JSON.stringify(res2));
},
fail: (err) => {
console.log('close failed: ', JSON.stringify(err));
}
});
},
onSearch() {
uni.openBluetoothAdapter({
success: (res) => {
console.log('res', res)
this.loading = true
this.isStop = false
this.startBluetoothDevicesDiscovery()
uni.onBluetoothAdapterStateChange((change) => {
console.log('adapterState changed, now is', change)
})
setTimeout(() => {
this.loading = false
this.stopBluetoothDevicesDiscovery()
}, 100000)
},
fail: (err) => {
this.initTypes(err.errCode)
console.log('openBluetoothAdapter err', err)
}
})
},
startBluetoothDevicesDiscovery() {
//在页面显示的时候判断是都已经初始化完成蓝牙适配器若成功,则开始查找设备
uni.startBluetoothDevicesDiscovery({
success: (res) => {
console.log('开始搜寻智能设备', res);
this.onBluetoothDeviceFound();
},
fail: (err) => {
uni.hideLoading()
console.log('查找设备失败:', err)
uni.showToast({ icon: 'none', title: '查找设备失败:', err, duration: 3000 })
}
});

        },  
        /**  
         * 停止搜索蓝牙设备  
         */  
        stopBluetoothDevicesDiscovery() {  
            uni.stopBluetoothDevicesDiscovery({  
                success: (result) => {  
                    this.loading = false  
                    console.log('停止搜索蓝牙设备:', result);  
                },  
                fail: (err) => {  
                    console.log('停止搜索蓝牙设备失败:', err);  
                }  
            })  
        },  
        /**  
         * 关闭蓝牙模块。调用该方法将断开所有已建立的连接并释放系统资源  
         */  
        closeBluetoothAdapter() {  
            uni.closeBluetoothAdapter({  
                success: (result) => {  
                    console.log('关闭蓝牙设备:', result);  
                },  
                fail: (err) => {  
                    console.log('关闭蓝牙设备失败:', err);  
                }  
            })  
        },  
        ab2hex(buffer) {  
          const hexArr = Array.prototype.map.call(  
            new Uint8Array(buffer),  
            function (bit) {  
              return ('00' + bit.toString(16)).slice(-2)  
            }  
          )  
          return hexArr.join('')  
        },  
        /**  
         * 发现外围设备  
         */  
        onBluetoothDeviceFound() {  
            if (this.loading) {  
                uni.onBluetoothDeviceFound((devices) => {  
                    console.log('开始监听寻找到新设备的事件', devices)  
                    this.getBluetoothDevices();  
                })  
            }  
        },  
        /**  
         * 获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备。  
         */  
        getBluetoothDevices() {  
            uni.getBluetoothDevices({  
                success: (result) => {  
                    console.log('获取蓝牙设备成功:', result)  
                    this.searchList = result.devices  
                    // this.searchList = result.devices.filter(item => item.name !== '未知设备')  
                    // this.searchList.forEach(item => {  
                    //  if (item.advertisData) {  
                    //      console.log('sss', this.ab2hex(item.advertisData))  
                    //  }  
                    // })  
                    uni.hideLoading()  
                    console.log()  
                },  
                fail: (err) => {  
                    uni.hideLoading()  
                    console.log('获取蓝牙设备失败:', err)  
                }  
            })  
        },  
        /**  
         * 根据 uuid 获取处于已连接状态的设备。  
         */  
        getConnectedBluetoothDevices() {  
            uni.getConnectedBluetoothDevices({  
                success: (result) => {  
                    console.log('getConnectedBluetoothDevices:', result)  
                },  
                fail: (err) => {  
                    console.log('uuid err', result)  
                }  
            })  
        },  
        /**  
         * 连接低功耗蓝牙  
         */  
        createBLEConnection(item) {  
            let deviceId = item.deviceId;  
            uni.showToast({  
                title: '连接蓝牙...',  
                icon: 'loading',  
                duration: 99999  
            });  
            uni.createBLEConnection({  
                // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接  
                deviceId,  
                success: res => {  
                    console.log(res);  
                    console.log('连接蓝牙成功:', res);  
                    // 连接设备后断开搜索 并且不能搜索设备  
                    this.stopBluetoothDevicesDiscovery(true);  
                    uni.hideToast();  
                    uni.showToast({  
                        title: '连接成功',  
                        icon: 'success',  
                        duration: 2000  
                    });  
                    this.selectList = [item]  
                    this.getBLEDeviceServices(item)  
                },  
                fail: e => {  
                    console.log('连接低功耗蓝牙失败:', e);  
                    if (e.errCode !== 0) this.initTypes(e.errCode)  
                }  
            });  
        },  
        getBLEDeviceServices(item) {  
            let deviceId = item.deviceId;  
            console.log('获取所有服务的 uuid:' + deviceId);  

            uni.getBLEDeviceServices({  
                // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接  
                deviceId,  
                success: res => {  
                    console.log(JSON.stringify(res.services));  
                    console.log('获取设备服务成功:', res);  
                    // this.showMaskType = 'service';  
                    // this.list = res.services;  
                    // this.characteristicsData = [];  
                    // if (this.list.length <= 0) {  
                    //  toast('获取服务失败,请重试!');  
                    //  return;  
                    // }  
                    // this.maskShow = true;  
                },  
                fail: e => {  
                    console.log('获取设备服务失败:', e);  
                    if (e.errCode !== 0) this.initTypes(e.errCode)  
                }  
            });  
        },  
        bluetooth_list(){  
            var main = plus.android.runtimeMainActivity();  
            var Context = plus.android.importClass("android.content.Context");  
            var BManager = main.getSystemService(Context.BLUETOOTH_SERVICE);  
            plus.android.importClass(BManager); //引入相关的method函数  
            var BAdapter = BManager.getAdapter();  
            plus.android.importClass(BAdapter);//引入相关的method函数,这样之后才会有isEna  
            var lists = BAdapter.getBondedDevices();  
            plus.android.importClass(lists);  
            // var resultDiv = document.getElementById('bluetooth_list');  
            var iterator = lists.iterator();  
            plus.android.importClass(iterator);  
            console.log("iterator", iterator);  
            while(iterator.hasNext()) {  
                var d = iterator.next();  
                plus.android.importClass(d);  
                console.log("名称:"+d.getName()+",地址:"+d.getAddress());  

            }  
        },  
        initTypes(code, errMsg) {  
            switch (code) {  
                case 10000:  
                    this.toast('未初始化蓝牙适配器');  
                    break;  
                case 10001:  
                    this.toast('未检测到蓝牙,请打开蓝牙重试!');  
                    break;  
                case 10002:  
                    this.toast('没有找到指定设备');  
                    break;  
                case 10003:  
                    this.toast('连接失败');  
                    break;  
                case 10004:  
                    this.toast('没有找到指定服务');  
                    break;  
                case 10005:  
                    this.toast('没有找到指定特征值');  
                    break;  
                case 10006:  
                    this.toast('当前连接已断开');  
                    break;  
                case 10007:  
                    this.toast('当前特征值不支持此操作');  
                    break;  
                case 10008:  
                    toast('其余所有系统上报的异常');  
                    break;  
                case 10009:  
                    this.toast('Android 系统特有,系统版本低于 4.3 不支持 BLE');  
                    break;  
                default:  
                    this.toast(errMsg || '未知错误');  
            }  
        },  
        toast(content, showCancel = false) {  
            uni.showModal({ title: '提示', content, showCancel });  
        },  
        /**  
         * 监听低功耗蓝牙连接状态的改变事件。包括开发者主动连接或断开连接,设备丢失,连接异常断开等等  
         */  
        onBLEConnectionStateChange() {  
            uni.onBLEConnectionStateChange(res => {  
                // 该方法回调中可以用于处理连接意外断开等异常情况  
                console.log(`蓝牙连接状态 -------------------------->`);  
                console.log(JSON.stringify(res));  
                if (!res.connected) {  
                    if(this.isStop) return ;  
                    this.toast('已经断开当前蓝牙连接');  
                }  
            });  
        },  
        onPlush() {  
            console.log('ddd')  
            var main, BAdapter, BluetoothAdapter, BluetoothDevice;    
            main = plus.android.runtimeMainActivity();    
            BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");    
            BAdapter = BluetoothAdapter.getDefaultAdapter();    
            BluetoothDevice = plus.android.importClass('android.bluetooth.BluetoothDevice');    
            console.log('7777')  
            //搜索设备接收器               
            var foundreceiver = plus.android.implements('io.dcloud.android.content.BroadcastReceiver', {    
                onReceive: function(context, intent) {    
                    console.log('context', context)  
                    plus.android.importClass(intent);    
                    console.log(intent.getAction());    
                    var BleDevice = new BluetoothDevice();    
                    BleDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);    
                    console.log("蓝牙设备:" + BleDevice.getName() + BleDevice.getAddress());    
                    main.unregisterReceiver(receiver);    
                }    
            });    
            console.log('8888', foundreceiver)  
            //注册接收器    
            var IntentFilterScan = plus.android.importClass('android.content.IntentFilter');    
            var filterScan = new IntentFilterScan();    
            filterScan.addAction(BluetoothDevice.ACTION_FOUND); //搜索设备                      
            main.registerReceiver(foundreceiver, filterScan); //注册监听  
        }  
    }  
}  

</script>

<style lang="scss">
.content {
.btn {
display: flex;
align-items: center;
justify-content: center;
button {
width: calc(100% / 2 - 20upx);
margin-right: 10upx;
}
}
.select-list,
.search-list {
padding: 0 20upx;
.title {
border-bottom: 1upx solid #e9eaec;
padding: 30upx 0;
}
.item {
border-bottom: 1upx solid #e9eaec;
text-align: center;
padding: 20upx 0;
}
}
}
</style>

2019-11-25 14:08 负责人:无 分享
已邀请:
LeexSAMA

LeexSAMA

同问,一样的情况

x***@163.com

x***@163.com

一样,获取不到蓝牙列表。onReceive不执行

1***@163.com

1***@163.com

都一年了,还没解决吗,

  • x***@163.com

    解决了,我也不知道怎么解决的,就是重新安排了一遍代码,更规范了,就成功了

    2021-02-23 15:10

  • y***@163.com

    回复 x***@163.com: 您好 我想问一下 您重新安排了一遍代码的意思是 name为空不是官方api的bug 而是我们代码不规范导致的嘛

    2022-11-03 11:38

  • 3***@qq.com

    回复 x***@163.com: name有了吗?

    2023-05-01 09:24

该问题目前已经被锁定, 无法添加新回复