在androidManifest里面添加
<uses-permission android:name = "android.permission.BLUETOOTH"/> <!--启用应用启动设备发现或者操作蓝牙设备的超级管理员--> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <uses-permission-sdk-23 android:name="android.permission.ACCESS_COARSE_LOCATION"/> Android5.0以上需要开启定位功能
/** * 定位权限 */ @SuppressLint("CheckResult") private void permissionLocation() { // if (context == null) return; // final RxPermissions rxPermissions = new RxPermissions(context); // rxPermissions.request(Manifest.permission.ACCESS_FINE_LOCATION).subscribe(new Consumer<Boolean>() { // @Override // public void accept(Boolean aBoolean) { // if (aBoolean) { // //申请的定位权限允许 // //设置整个连接过程超时时间 // workHandler.sendEmptyMessageDelayed(LINK_TIME_OUT, linkTime); // //如果可以Mac直连则不扫描 // if (isDirectConnect()) { // Log.d(TAG, "此次为MAC地址直连"); // workHandler.sendEmptyMessage(CONNECT_GATT); // } else { // Log.d(TAG, "此次为蓝牙扫描连接"); // workHandler.sendEmptyMessage(START_SCAN); // } // } else { // //只要有一个权限被拒绝,就会执行 // Log.d(TAG, "未授权定位权限,蓝牙功能不能使用:"); // Toast.makeText(context, "未授权定位权限,蓝牙功能不能使用", Toast.LENGTH_LONG).show(); // } // } // }); }
蓝牙开发主要是通过BlueToothAdapter类来获取蓝牙相关的一些属性
val mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
if (mBluetoothAdapter == null) { // 说明此设备不支持蓝牙操作 Toast.makeText(this, "当前设备不支持蓝牙", Toast.LENGTH_SHORT).show() } // 没有开始蓝牙 if (!mBluetoothAdapter.isEnabled) { Toast.makeText(this, "蓝牙未开启", Toast.LENGTH_SHORT).show() } 通过mBluetoothAdapter.enable()开启蓝牙,mBluetoothAdapter.disable()关闭蓝牙,也可以通过隐式跳转手动开启或关闭蓝牙。
搜索蓝牙设备有两种情况,一种是搜索已经配对过的设备通过
// val pairedDevices: Set<BluetoothDevice> = mBluetoothAdapter.getBondedDevices() // if (pairedDevices.size > 0) { // for (device in pairedDevices) { // // 把名字和地址取出来添加到适配器中 // arrayList.add( // """ // ${device.name} // ${device.address} // """.trimIndent() // ) // } // }
另一种就是搜索所有的设备,这样就需要开启service服务来获取
//开启蓝牙搜索 mBluetoothAdapter.startDiscovery()
//关闭蓝牙搜索 mBluetoothAdapter.cancelDiscovery()
val bluetoothReceiver: BroadcastReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent) { val action = intent.action if (BluetoothDevice.ACTION_FOUND == action) { val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE) if (device == null || device!!.name == null) return arrayList.add( """ 设备名:${device!!.name} 设备地址:${device!!.address} """.trimIndent() ) //将搜索到的蓝牙名称和地址添加到列表。 // arrayList.add(device!!.address) //将搜索到的蓝牙地址添加到列表。 bluetooth.notifyDataSetChanged() //更新 } } }
如何获取蓝牙设备的UUID
1.如果设备配对过的话
BluetoothSocket socket=shouldOperateBluetoothDevice.createInsecureRfcommSocketToServiceRecord(UUID.randomUUID()); BluetoothDevice remoteDevice = socket.getRemoteDevice();
ParcelUuid[] uuids = remoteDevice.getUuids();
for (ParcelUuid uuid : uuids) { Log.d(TAG, "uuid--" + uuid; }
2.如果设备未配对过
val mRunnable = Runnable { run { var mDevice = mBluetoothAdapter.getRemoteDevice("") var bluetoothGatt = mDevice.connectGatt( this, false, object : BluetoothGattCallback() { override fun onConnectionStateChange( gatt: BluetoothGatt?, status: Int, newState: Int ) { if (newState == BluetoothProfile.STATE_CONNECTED) { // Log.i("1231231","启动服务发现"+bluetoothGatt.discoverServices()) } } override fun onServicesDiscovered(gatt: BluetoothGatt?, status: Int) { if (status == BluetoothGatt.GATT_SUCCESS) { // broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED); Log.d("TAG", "onServicesDiscovered--" + "ACTION_GATT_SERVICES_DISCOVERED"); var bluetoothGattServices = gatt?.getServices(); //发现服务是可以在这里查找支持的所有服务 // BluetoothGattService bluetoothGattService = gatt.getService(UUID.randomUUID()); if (bluetoothGattServices != null) { for ( bluetoothGatt in bluetoothGattServices) { //设备的UUID var uuid = bluetoothGatt.getUuid(); } } } else { Log.w("TAG", "onServicesDiscovered received: " + status); System.out.println("onServicesDiscovered received: " + status); } } override fun onCharacteristicRead( gatt: BluetoothGatt?, characteristic: BluetoothGattCharacteristic?, status: Int ) { super.onCharacteristicRead(gatt, characteristic, status) } override fun onCharacteristicChanged( gatt: BluetoothGatt?, characteristic: BluetoothGattCharacteristic? ) { super.onCharacteristicChanged(gatt, characteristic) } } ) } } Thread(mRunnable).start() }
可以获取到UUID