uniapp基于native.js扫描经典蓝牙设备

本文介绍了在Android中使用JavaScript实现蓝牙设备扫描,通过BroadcastReceiver监听`ACTION_FOUND`事件,检测蓝牙设备是否已配对并记录未配对设备信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

版本1,好像个别情况时不可用。

bluetooth_list2() {
				//扫描蓝牙  http://ask.dcloud.net.cn/article/643   
				var main = plus.android.runtimeMainActivity();
				var IntentFilter = plus.android.importClass('android.content.IntentFilter');
				var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
				var BluetoothDevice = plus.android.importClass("android.bluetooth.BluetoothDevice");
				var BAdapter = BluetoothAdapter.getDefaultAdapter();
				console.log("开始搜索设备");
				var filter = new IntentFilter();
				var bdevice = new BluetoothDevice();
				var on = null;
				var un = null;
				var msg = "";
				BAdapter.startDiscovery(); //开启搜索  
				var receiver;
				receiver = plus.android.implements('io.dcloud.android.content.BroadcastReceiver', {
					onReceive: function(context, intent) { //实现onReceiver回调函数  
						plus.android.importClass(intent); //通过intent实例引入intent类,方便以后的‘.’操作  
						console.log(intent.getAction()); //获取action  
						if (intent.getAction() == "android.bluetooth.adapter.action.DISCOVERY_FINISHED") {
							main.unregisterReceiver(receiver); //取消监听  
							console.log("搜索结束")
						} else {
							var BleDevice = new BluetoothDevice();  
							BleDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
							//判断是否配对  
							if (BleDevice.getBondState() == bdevice.BOND_NONE) {
								var msg1 = "未配对蓝牙设备:" + BleDevice.getName() + ",地址:" + BleDevice.getAddress() + "<br/>";
								console.log(msg1);
								msg += msg1;
								_this.info2 = msg;
								// console.log("未配对蓝牙设备:" + BleDevice.getName() + '    ' + BleDevice.getAddress());
								
							} else {
								if (BleDevice.getName() != un) { //判断防止重复添加  
									// console.log("已配对蓝牙设备:" + BleDevice.getName() + '    ' + BleDevice.getAddress());
									var msg1 = "未配对蓝牙设备:" + BleDevice.getName() + ",地址:" + BleDevice.getAddress() + "<br/>";
									console.log(msg1);
									msg += msg1;
									_this.info2 = msg;	
								}
							}
						}

					}
				});

				filter.addAction(bdevice.ACTION_FOUND);
				// filter.addAction(BAdapter.ACTION_DISCOVERY_STARTED);
				filter.addAction(BAdapter.ACTION_DISCOVERY_FINISHED);
				filter.addAction(BAdapter.ACTION_STATE_CHANGED);

				main.registerReceiver(receiver, filter); //注册监听  
				
				console.log('end code');
			},

版本2:
APP经典原生蓝牙插件(Android原生) - DCloud 插件市场 https://ext.dcloud.net.cn/plugin?id=16076
测试成功。 与版本1方法类似。

	openBluetoothAdapter() {
				//未打开蓝牙点击搜索蓝牙提示弹窗
				if(this.bluetooth == 1){
					uni.showToast({
						title: "请先打开蓝牙",
						icon:"error"
					})
					return;
				}
				let system = uni.getSystemInfoSync(); // 获取系统信息
				if (system.platform === 'android') { // 判断平台
				  var that = this;
				  var context = plus.android.importClass("android.content.Context");
				  var locationManager = plus.android.importClass("android.location.LocationManager");
				  var main = plus.android.runtimeMainActivity();
				  var mainSvr = main.getSystemService(context.LOCATION_SERVICE);
				  // 定位检测
				  if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
					  uni.showModal({
						title: "提示",
						content: "请打开定位服务功能",
						showCancel: false, // 不显示取消按钮
						success() {
						  if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
							var Intent = plus.android.importClass('android.content.Intent');
							var Settings = plus.android.importClass('android.provider.Settings');
							var intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
							main.startActivity(intent); // 打开系统设置GPS服务页面
						  } else {
							console.log('GPS功能已开启');
						}
					  }
				   });
				  return false
				  } else {
					console.log('GPS功能已开启');
					that.searchDevices()
					return true
				  }
				}
			},
			
			//搜索蓝牙
			searchDevices(){
				var that = this;
				that.unpairedList = [];	//未配对
				// that.pairedList = []; 	//已配对
				
				//取内存里面已配对的蓝牙
				// that.pairedList = uni.getStorageSync("pairedList");
				
				//打开蓝牙模块
				uni.openBluetoothAdapter({
					success(res) {
						console.log("蓝牙模块:",res);
						//获取本机蓝牙适配器状态
						uni.getBluetoothAdapterState({
							success: function(res) {
								console.log("蓝牙适配器状态:",res);
								if (res.available) {
									//开始搜寻附近的蓝牙外围设备
									uni.startBluetoothDevicesDiscovery({
										success(res) {
											var main = plus.android.runtimeMainActivity();
											var IntentFilter = plus.android.importClass('android.content.IntentFilter');
											var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
											var BluetoothDevice = plus.android.importClass("android.bluetooth.BluetoothDevice");
											var BAdapter = BluetoothAdapter.getDefaultAdapter();
											
											if (BAdapter != null && !BAdapter.isEnabled()) {
											  let _intent = plus.android.importClass('android.content.Intent');
											  let intent = new _intent(blue_client.ACTION_REQUEST_ENABLE);
											  main.startActivityForResult(intent, 200);
											}
											
											uni.showLoading({
											  title: "开始搜索设备",
											})
											
											//获取本机蓝牙信息
											// var name = BAdapter.getName();
											// var address = BAdapter.getAddress();
											// console.log("本机蓝牙名称:"+name+" 本机蓝牙地址:"+address);
											
											var filter = new IntentFilter();
											var bdevice = new BluetoothDevice();
											BAdapter.startDiscovery(); //开启搜索  
											var receiver;
											receiver = plus.android.implements('io.dcloud.android.content.BroadcastReceiver', {onReceive: function(context, intent) { //实现onReceiver回调函数  
												plus.android.importClass(intent); //通过intent实例引入intent类,方便以后的‘.’操作
												if (intent.getAction() == "android.bluetooth.adapter.action.DISCOVERY_FINISHED") {
													main.unregisterReceiver(receiver); //取消监听
													//去重
													// for (let i = 0; i < that.unpairedList.length; i++) {
													// 	for (let j = i+1; j < that.unpairedList.length; j++) {
													// 		if(that.unpairedList[i].address == that.unpairedList[j].address){
													// 			that.unpairedList.splice(j,1);//去重
													// 			j--;
													// 		}
													// 	}
													// }
													// for (let i = 0; i < that.pairedList.length; i++) {
													// 	for (let j = i+1; j < that.pairedList.length; j++) {
													// 		if(that.pairedList[i].address == that.pairedList[j].address){
													// 			that.pairedList.splice(j,1);//去重
													// 			j--;
													// 		}
													// 	}
													// }
													console.log("搜索结束");
													console.log(that.unpairedList);
													// console.log(that.pairedList);
													//把已配对的蓝牙存内存
													// uni.setStorageSync("pairedList",that.pairedList);
													uni.hideLoading();
												} else {
													if (intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE).getBondState() === 10) {
														var y = 0;
														for (let x = 0; x < that.unpairedList.length; x++) {
															if(that.unpairedList[x].address == intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE).getAddress()){
																y++;
															}
														}
														if(y > 0){
															y = 0;
														}else{
															that.unpairedList.push({
																name: intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE).getName(),
																address: intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE).getAddress()
															})
														}
													}
													// else if (intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE).getBondState() === 12) {
													// 	var y = 0;
													// 	for (let x = 0; x < that.pairedList.length; x++) {
													// 		if(that.pairedList[x].address == intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE).getAddress()){
													// 			y++;
													// 		}
													// 	}
													// 	if(y > 0){
													// 		y = 0;
													// 	}else{
													// 		that.pairedList.push({
													// 			name: intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE).getName(),
													// 			address: intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE).getAddress(),
													// 			isSelected:'0'
													// 		})
													// 	}
													// }
												}
											}});
											filter.addAction(bdevice.ACTION_FOUND);
											filter.addAction(BAdapter.ACTION_DISCOVERY_STARTED);
											filter.addAction(BAdapter.ACTION_DISCOVERY_FINISHED);
											filter.addAction(BAdapter.ACTION_STATE_CHANGED);
											main.registerReceiver(receiver, filter); //注册监听
										}
									})
								}
							},
						})
					}
				})
			},
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值