赞
踩
目录
1、connectGatt(context, false, bluetoothGattCallback)方法
3、读取特征值 gatt.readCharacteristic(characteristic)
6、断开连接bluetoothGatt.disconnect()
清单文件 AndroidManifest.xml:
- <!-- 蓝牙权限 -->
- <uses-permission
- android:name="android.permission.BLUETOOTH"
- android:maxSdkVersion="30" />
- <uses-permission
- android:name="android.permission.BLUETOOTH_ADMIN"
- android:maxSdkVersion="30" />
- <!-- 位置权限 -->
- <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
- <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
- <!-- 安卓12蓝牙权限 -->
- <!-- 扫描权限 -->
- <uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
- <!-- 蓝牙可被发现权限 -->
- <uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
- <!-- 连接权限 -->
- <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
- <!-- 声明应用需要支持BLE -->
- <uses-feature
- android:name="android.hardware.bluetooth_le"
- android:required="true" />
以上为蓝牙需要的权限(适配安卓12)
1、蓝牙单例类BleManager.java:
- /**
- * author:created by mj
- * Date:2022/6/7 17:33
- * Description:蓝牙单例类
- */
- public class BleManager {
- //单例对象
- public static volatile BleManager bleManager;
-
- //调用到上下文对象
- private FragmentActivity context;
-
- //蓝牙适配器
- private BluetoothManager bluetoothManager;
- private BluetoothAdapter bluetoothAdapter;
-
- //设备扫描
- private BluetoothLeScanner bleScanner;
-
- //扫描回调 区分高低版本 H为安卓5.0及以上版本
- private ScanCallback scanCallbackH;
- private BluetoothAdapter.LeScanCallback scanCallbackL;
-
- //蓝牙gatt服务对象和回调
- private BluetoothGatt bluetoothGatt;
- private BluetoothGattCallback bluetoothGattCallback;
-
- //设备和app之间的读写特征值和描述符
- private BluetoothGattCharacteristic readCharacteristic;
- private BluetoothGattCharacteristic writeCharacteristic;
- private BluetoothGattDescriptor readDescriptor;
-
- //判断是否正在扫描和是否连接设备
- public boolean isScanning = false;
- public boolean isConnect = false;
-
- //子线程
- private Handler workHandler;
- private HandlerThread handlerThread;
-
- //主线程
- private Handler mainHandler;
-
- //存放扫描到的设备
- private List<String> devicesList;
- //存放配对的设备名字和mac地址
- private SharedPreferences sp;
-
-
- //服务和特征值ID(由ble设备工程师设置)
- private final String SERVICE_UUID = "0000xxxx-0000-1000-8000-xxxxxxxxxxxx";
- private final String CHARACTERISTIC_UUID1 = "0000xxxx-0000-1000-8000-xxxxxxxxxxxx";
- private final String CHARACTERISTIC_UUID2 = "0000xxxx-0000-1000-8000-xxxxxxxxxxxx";
- private final String READ_DESCRIPTOR_UUID = "00002902-0000-1000-8000-00805f9b34fb";
-
- //已配对的蓝牙设备
- private BluetoothDevice bleDevice;
- //设备名字和Mac地址
- private String DEVICE_NAME;
- private String DEVICE_ADDRESS;
-
- //ble状态码用来多线程处理
- private static final int START_SCAN = 1;
- private static final int STOP_SCAN = 2;
- private static final int CONNECT_GATT = 3;
- private static final int DISCONNECT_GATT = 4;
- private static final int CLOSE_GATT = 5;
- private static final int SEND_DATA = 6;
-
- //权限申请
- private BlePermissionHelper blePermissionHelper;
-
- //蓝牙连接状态改变监听接口
- private OnBleConnectCallback onBleConnectCallback;
-
-
- public interface OnBleConnectCallback {
- //扫描到设备
- void bleScan();
-
- //蓝牙设备连接和断开
- void bleConnect();
-
- void bleDisConnect();
-
- //获取设备电量
- void getBleEleQue(int ele);
- }
-
- //获取单例模式(懒汉式)
- public static BleManager getInstance() {
- //双重校验锁(提高效率)
- if (bleManager == null)
- synchronized (BleManager.class) {
- if (bleManager == null)
- bleManager = new BleManager();
- }
- return bleManager;
- }
-
- //初始化蓝牙ble相关
- @SuppressLint({"MissingPermission", "ObsoleteSdkInt"})
- public void initBle(FragmentActivity activity) {
- this.context = activity;
- devicesList = new ArrayList<>();
- //请求权限
- blePermissionHelper = new BlePermissionHelper(activity);
- if (!blePermissionHelper.isSupportBLE()) {
- Toast.makeText(activity, "当前设备不支持蓝牙!", Toast.LENGTH_LONG).show();
- return;
- }
- //通过蓝牙管理器获取适配器
- bluetoothManager = (BluetoothManager) activity.getApplicationContext().getSystemService(Context.BLUETOOTH_SERVICE);
- bluetoothAdapter = bluetoothManager.getAdapter();
- //android 5.0以上API需要的ble扫描类
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
- //初始化scanner
- bleScanner = bluetoothAdapter.getBluetoothLeScanner();
-
- //初始化已配对设备名和地址
- sp = activity.getApplicationContext().getSharedPreferences("sp_ble", Context.MODE_PRIVATE);
- DEVICE_NAME = sp.getString("bleName", null);
- DEVICE_ADDRESS = sp.getString("bleAddress", null);
-
- //初始化线程
- initHandler();
-
- //初始化高版本api扫描回调
- scanCallbackH = new ScanCallback() {
- @SuppressLint("MissingPermission")
- @Override
- public void onScanResult(int callbackType, ScanResult result) {
- super.onScanResult(callbackType, result);
- //连接蓝牙
- //进行扫描到的设备过滤
- if (result.getDevice().getName() == null)
- return;
- // Log.e("test","nowName "+DEVICE_NAME+" scanName "+bleDevice.getName() +" if="+bleDevice.getName().equals(DEVICE_NAME));
- //这里根据设备名进行连接(可以使用mac地址)
- if (result.getDevice().getName().equals(DEVICE_NAME)) {
- bleDevice = result.getDevice();
- mainHandler.sendEmptyMessage(CONNECT_GATT);
- }
- Log.e("test", "name:" + result.getDevice().getName() + " rssi:" + result.getRssi() + " address:" + result.getDevice().getAddress());
- if (devicesList.contains(result.getDevice().getName()))
- return;
- //将扫描到到设备添加到集合中用于显示
- devicesList.add(result.getDevice().getName());
- //回调连接接口的扫描方法
- onBleConnectCallback.bleScan();
-
- }
- };
-
- //初始化低版本api扫描回调
- scanCallbackL = new BluetoothAdapter.LeScanCallback() {
- @Override
- public void onLeScan(BluetoothDevice bluetoothDevice, int i, byte[] bytes) {
- //内容同上onScanResult方法
-
- }
- };
-
-
- //初始化蓝牙gatt回调
- bluetoothGattCallback = new
- BluetoothGattCallback() {
- @SuppressLint("MissingPermission")
- @Override
- public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
- super.onConnectionStateChange(gatt, status, newState);
- Log.e("test", "onConnectionStateChange " + newState);
- //连接蓝牙成功后发现可读写的服务
- if (newState == BluetoothGatt.STATE_CONNECTED) {
- //连接成功后停止扫描
- workHandler.sendEmptyMessage(STOP_SCAN);
- DEVICE_NAME = gatt.getDevice().getName();
- // onBleConnectCallback.bleConnect();
- DEVICE_ADDRESS = gatt.getDevice().getAddress();
- Log.e("test", "connect name :" + DEVICE_NAME + " address---" + DEVICE_ADDRESS);
- isConnect = true;
- //将已连接的设备名存储到SharedPreferences中
- //先从sp中获取ble设备信息
- SharedPreferences.Editor editor = sp.edit();
- editor.putString("bleName", DEVICE_NAME);
- editor.apply();
- //延迟后回调否则扫描失败没有回调
- // handler.postDelayed(gatt::discoverServices, 100);
- bluetoothGatt.discoverServices();
- return;
- }
- if (newState == BluetoothGatt.STATE_DISCONNECTED) {
- onBleConnectCallback.bleDisConnect();
- isConnect = false;
- mainHandler.sendEmptyMessage(CLOSE_GATT);
- return;
- }
- //避免其他情况出现,断开连接
- mainHandler.sendEmptyMessage(DISCONNECT_GATT);
- }
-
- @SuppressLint("MissingPermission")
- @Override
- public void onServicesDiscovered(BluetoothGatt gatt, int status) {
- super.onServicesDiscovered(gatt, status);
- //发现服务成功后寻找特征值
- if (status == BluetoothGatt.GATT_SUCCESS) {
- UUID serviceUuid = UUID.fromString(SERVICE_UUID);
- //读设备到app的特征值uuid
- UUID characteristicUuid1 = UUID.fromString(CHARACTERISTIC_UUID1);
- //写app到设备的特征值uuid
- UUID characteristicUuid2 = UUID.fromString(CHARACTERISTIC_UUID2);
- bluetoothGatt.getServices();
- BluetoothGattService gattService = bluetoothGatt.getService(serviceUuid);
- if (gattService != null) {
- //根据uuid获取相应特征值
- readCharacteristic = gattService.getCharacteristic(characteristicUuid1);
- writeCharacteristic = gattService.getCharacteristic(characteristicUuid2);
- //获取根据uuid获取相应描述
- readDescriptor = readCharacteristic.getDescriptor(UUID.fromString(READ_DESCRIPTOR_UUID));
- //设置描述和特征值通知
- readDescriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
- bluetoothGatt.writeDescriptor(readDescriptor);
- bluetoothGatt.setCharacteristicNotification(readCharacteristic, true);
- //获取电量
- // handler.postDelayed(() -> writeBleHexStrValue("A102010055"), 200);
- }
- }
- }
-
- //读取数据回调,接收数据
- @Override
- public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic
- characteristic, int status) {
- super.onCharacteristicRead(gatt, characteristic, status);
- if (characteristic.getUuid().toString().equals(CHARACTERISTIC_UUID1)) {
- byte[] value = characteristic.getValue();
- Log.e("test", "Read" + Arrays.toString(value));
- }
- }
-
- //发送数据回调
- @Override
- public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic
- characteristic, int status) {
- super.onCharacteristicWrite(gatt, characteristic, status);
- byte[] value = characteristic.getValue();
- Log.e("test", "Write" + Arrays.toString(value));
- }
-
- //蓝牙设备改变特征值后接收修改的信息
- @Override
- public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic
- characteristic) {
- super.onCharacteristicChanged(gatt, characteristic);
- //判断是否为指定的特征值
- if (characteristic.getUuid().toString().equals(CHARACTERISTIC_UUID1)) {
- byte[] value = characteristic.getValue();
- //判断返回的数据是否非空且为电量
- if (value == null || value.length <= 0 || value[1] != 0x02)
- return;
- electricQuantity = value[3] & 0xFF;
- }
- byte[] value = characteristic.getValue();
- Log.e("test", "CharacteristicChanged " + Arrays.toString(value));
- onBleConnectCallback.getBleEleQue(electricQuantity);
- }
-
- //设置描述符后回调
- @Override
- public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
- super.onDescriptorWrite(gatt, descriptor, status);
- if (status == BluetoothGatt.GATT_SUCCESS) {
- Log.e("test", "onDescriptorWrite success");
- //设置特征通知成功,发送数据的特征也是成功,可以相互收发数据了
- //获取电量
- workHandler.postDelayed(() -> sendData2Ble("A102010055"), 100);
-
- }
-
- }
- }
-
- ;
- }
-
- //初始化线程
- private void initHandler() {
- //初始化主线程
- mainHandler = new Handler(context.getMainLooper()) {
- @SuppressLint("MissingPermission")
- @Override
- public void handleMessage(@NonNull Message msg) {
- super.handleMessage(msg);
- switch (msg.what) {
- case CONNECT_GATT:
- bluetoothGatt = bleDevice.connectGatt(context, false, bluetoothGattCallback);
- break;
- case DISCONNECT_GATT:
- if (bluetoothGatt != null)
- bluetoothGatt.disconnect();
- break;
- case CLOSE_GATT:
- if(bluetoothGatt!=null)
- bluetoothGatt.close();
- bluetoothGatt = null;
- break;
- }
- }
- };
-
- //初始化工作子线程
- handlerThread = new HandlerThread("BleWorkHandlerThread");
- handlerThread.start();
- workHandler = new Handler(handlerThread.getLooper()) {
- @SuppressLint("MissingPermission")
- @Override
- public void handleMessage(@NonNull Message msg) {
- super.handleMessage(msg);
- //根据消息类别进行相应处理
- switch (msg.what) {
- case START_SCAN:
- startBleScan();
- break;
- case STOP_SCAN:
- if (isScanning) {
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
- if (bleScanner == null)
- bleScanner = bluetoothAdapter.getBluetoothLeScanner();
- bleScanner.stopScan(scanCallbackH);
- }
- else
- bluetoothAdapter.stopLeScan(scanCallbackL);
- isScanning = false;
- }
- //线程休眠确保ble停止搜索完成
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- break;
- case SEND_DATA:
- writeBleHexStrValue((String) msg.obj);
- break;
- }
- }
- };
-
- }
-
- //搜索蓝牙设备方法
- public void scanLeDevice() {
- if (blePermissionHelper.checkNOpenGps() && blePermissionHelper.checkNOpenBl()) {
- workHandler.sendEmptyMessage(START_SCAN);
- Log.e(TAG, "scan start");
- }
- }
- //停止扫描方法
- public void stopScanLeDevice() {
- workHandler.sendEmptyMessage(STOP_SCAN);
- }
- //向蓝牙设备写入数据方法
- @SuppressLint("MissingPermission")
- public void writeBleHexStrValue(String hexStr) {
- //判断是否连接和数据值是否为空
- if (!isConnect || hexStr == null || hexStr.equals(""))
- return;
- //判断写特征值和服务对象是否为空
- if (writeCharacteristic == null || bluetoothGatt == null)
- return;
- byte[] value = hexStrToBytes(hexStr);
- writeCharacteristic.setValue(value);
- bluetoothGatt.writeCharacteristic(writeCharacteristic);
- }
-
- //发送数据到BLE设备
- private void sendData2Ble(String data) {
- Message message = new Message();
- message.what = SEND_DATA;
- message.obj = data;
- workHandler.sendMessage(message);
- }
-
- //16进制字符串转字节数组
- public static byte[] hexStrToBytes(String hexStr) {
- String hex = "0123456789ABCDEF";
- if (hexStr == null || hexStr.equals(""))
- return null;
- //全部转化为大写字母
- hexStr = hexStr.toUpperCase();
- //字节数组长度
- int length = hexStr.length() / 2;
- //转化为字符数组
- byte[] value = new byte[length];
- char[] hexChar = hexStr.toCharArray();
- for (int i = 0; i < length; i++) {
- int p = i * 2;
- //右移4位得到字节高位再和下一个字符或得到位
- value[i] = (byte) (hex.indexOf(hexChar[p]) << 4 | hex.indexOf(hexChar[p + 1]));
- }
- return value;
- }
-
-
- //设置回调接口
- public void setOnBleConnectCallback(OnBleConnectCallback onBleConnectCallback) {
- this.onBleConnectCallback = onBleConnectCallback;
- }
-
- //开始扫描蓝牙
- @SuppressLint({"MissingPermission", "ObsoleteSdkInt"})
- public void startBleScan() {
- if (!isScanning) {
- isScanning = true;
- Log.e("test", "扫描");
- //开始扫描
- //如果安卓版本高于5.0使用高版本api
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
- if (bleScanner == null)
- bleScanner = bluetoothAdapter.getBluetoothLeScanner();
- bleScanner.startScan(scanCallbackH);
- }
- else
- bluetoothAdapter.startLeScan(scanCallbackL);
- }
- }
-
- //判断蓝牙打开状态
- public boolean isEnabled() {
- return bluetoothAdapter.isEnabled();
- }
-
- //getter和setter 方法
- public BluetoothAdapter getBluetoothAdapter() {
- return bluetoothAdapter;
- }
2、权限处理类PermissionHelper.java
- /**
- * author:created by mj
- * Date:2022/8/24 17:30
- * Description:用于权限的类
- */
- public class BlePermissionHelper {
- private static final String TAG = "BlePermissionHelper";
- private Activity mActivity;
- private Context mContext;
- private final String[] gpsPermissions = new String[]{ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION};
- private final String[] blPermissions = new String[]{BLUETOOTH_SCAN, BLUETOOTH_CONNECT};
-
- private final BluetoothAdapter bluetoothAdapter;
- private final LocationManager locationManager;
-
- //状态码
- private final int OPEN_BLUETOOTH = 1;
- public final int REQUEST_GPS_PERMISSIONS = 2;
- public final int REQUEST_BLUETOOTH_PERMISSIONS = 3;
- //权限提示对话框
- private AlertDialog mDialog;
-
-
- public BlePermissionHelper(Activity mActivity) {
- this.mActivity = mActivity;
- this.mContext = mActivity;
- this.bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
- this.locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
- AlertDialog.Builder builder = new AlertDialog.Builder(this);
- builder.setTitle("获取权限")
- .setMessage("设置允许权限后才可以使用")
- .setPositiveButton("设置", (dialog, id) -> {
- Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
- Uri uri = Uri.fromParts("package", getPackageName(), null);
- intent.setData(uri);
- startActivity(intent);
- finish();
- }).setNegativeButton("取消", null);
- //弹出对话框提示
- AlertDialog mDialog = builder.create();
- mDialog.setCanceledOnTouchOutside(true);
- }
-
- public BlePermissionHelper(Context context) {
- this.mContext = context;
- this.bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
- this.locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
- }
-
- //动态申请位置权限
- public void requestGpsPermissions() {
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
- if (!isLocationPermission()) {
- Log.e(TAG, "request gps permission");
- // 没有权限会弹出对话框申请
- ActivityCompat.requestPermissions(mActivity, gpsPermissions, REQUEST_GPS_PERMISSIONS);
- }
- }
-
- //动态申请蓝牙权限(安卓12以上)
- public void requestBlePermissions() {
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
- if (!isBlPermission()) {
- Log.e(TAG, "request bl ");
- // 没有权限会弹出对话框申请
- ActivityCompat.requestPermissions(mActivity, blPermissions, REQUEST_BLUETOOTH_PERMISSIONS);
- }
- }
- }
-
- //检查权限和打开GPS
- public boolean checkNOpenGps() {
- if (!isLocationPermission()) {
- requestGpsPermissions();
- return false;
- }
- if (!isEnableGps()) {
- mActivity.startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
- return false;
- }
- return true;
- }
-
-
- //检查权限和打开蓝牙
- @SuppressLint("MissingPermission")
- public boolean checkNOpenBl() {
- if (!isBlPermission()) {
- requestBlePermissions();
- return false;
- }
- if (!isEnableBluetooth()) {
- //执行一次打开蓝牙功能,给用户提示。
- Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
- mActivity.startActivityForResult(intent, OPEN_BLUETOOTH);
- return false;
- }
- return true;
- }
-
-
- //判断是否支持ble
- public boolean isSupportBLE() {
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
- return false;
- }
- return mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE);
- }
-
- //判断是否打开蓝牙
- public boolean isEnableBluetooth() {
- if (!isSupportBLE())
- return false;
- return bluetoothAdapter.isEnabled();
- }
-
- //判断是否打开gps定位
- public boolean isEnableGps() {
- return locationManager.isProviderEnabled(GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
- }
-
- //判断是否授权gps
- public boolean isLocationPermission() {
- return checkSelfPermission(mContext, ACCESS_COARSE_LOCATION) == PERMISSION_GRANTED
- || checkSelfPermission(mContext, ACCESS_FINE_LOCATION) == PERMISSION_GRANTED;
- }
-
- //判断是否授权蓝牙(安卓12以上)
- public boolean isBlPermission() {
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
- return checkSelfPermission(mContext, BLUETOOTH_CONNECT) == PERMISSION_GRANTED
- && checkSelfPermission(mContext, BLUETOOTH_SCAN) == PERMISSION_GRANTED;
- }
- return true;
- }
-
- //如果用户选择了不再询问权限则弹窗提醒
- public void showSetPermissionDialogIfDeny(int requestCode) {
- String[] permissions;
- if (requestCode == REQUEST_GPS_PERMISSIONS) {
- if (isLocationPermission()) {
- requestBlePermissions();
- return;
- }
- permissions = gpsPermissions;
-
- } else {
- permissions = blPermissions;
- }
- for (String permission : permissions) {
- //用户选择了禁止且不再询问
- if (!ActivityCompat.shouldShowRequestPermissionRationale(mActivity, permission) && ActivityCompat.checkSelfPermission(mActivity, permission) != PackageManager.PERMISSION_GRANTED) {
- Log.e(TAG, "show dialog" + permission);
- if (!mDialog.isShowing())
- //弹出对话框提示
- mDialog.show();
- break;
- }
- }
- }
-
- //请求单个权限方法
- public void requestPermission(String permission, int requestCode) {
- if (checkSelfPermission(mContext, permission) != PERMISSION_GRANTED)
- ActivityCompat.requestPermissions(mActivity, new String[]{permission}, requestCode);
- }
-
- }
3、界面中使用ble单例类相关代码
- public class PermissionActivity extends AppCompatActivity {
- private BlePermissionHelper blePermissionHelper;
- private BleManager ble;
- @Override
- protected void onCreate(@Nullable Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- ble = BleManager.getInstance();
- ble.initBle(MainActivity.this);
- blePermissionHelper = new BlePermissionHelper(this);
- //ble连接回调
- BleManager.OnBleConnectCallback bleConnectCallback = new BleManager.OnBleConnectCallback() {
- @Override
- public void bleScan() {
-
- }
-
- @Override
- public void bleConnect() {
-
- }
-
- @Override
- public void bleDisConnect() {
-
- }
-
- @Override
- public void getBleEleQue(int ele) {
-
- }
- };
- ble.setOnBleConnectCallback(bleConnectCallback);
-
- }
-
- //权限回调方法
- @Override
- public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
- super.onRequestPermissionsResult(requestCode, permissions, grantResults);
- for (String p : permissions)
- Log.e("TAG", "onRequestPermissionsResult: " + requestCode + " " + p);
- blePermissionHelper.showSetPermissionDialogIfDeny(requestCode);
- }
- }
1、connectGatt(context, false, bluetoothGattCallback)方法
第二个参数自动连接一般设为false,设置为true有时候会导致连接成功但无法读写数据的情况(据说如果自动连接期间再建立一个连接会出现死循环)。自动连接的效率也很低,不如自己写回连逻辑。
2、设置接收特定特征通知
特征改变时需要获取数据只有
bluetoothGatt.setCharacteristicNotification(readCharacteristic, true);
不行,还要在上述语句前面加上下面两行代码设置相应的特征里的描述符的通知。
- //获取根据uuid获取相应描述
- readDescriptor = readCharacteristic.getDescriptor(UUID.fromString(READ_DESCRIPTOR_UUID));
- //设置描述通知
- readDescriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
- bluetoothGatt.writeDescriptor(readDescriptor);
注意setValue方法是BluetoothGattDescriptor对象调用的而不是BluetoothGattCharacteristic对象,这里写反编译器不会报错,但是无法接收到notify消息。
3、读取特征值 gatt.readCharacteristic(characteristic)
复杂一点的情况下一般都需要加一个延迟再读,否则经常读不到返回false。(也可能与设备有关)
4、连接同时拥有经典蓝牙和BLE的设备
可能会出现无法连接的情况 Log显示onClientConnectionState() - status=133 clientIf=10
这时候需要修改连接代码对安卓6.0以上增加一个参数。
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
- mBluetoothGatt = mBluetoothDevice.connectGatt(mContext, false, mGattCallback,BluetoothDevice.TRANSPORT_LE);
- } else {
- mBluetoothGatt = mBluetoothDevice.connectGatt(mContext, false, mGattCallback);
- }
5、设置MTU
设置MTU要等onMtuChanged回调后再进行读写操作,不然的话会导致后续的读写特征返回false,无法发送数据到设备。
6、断开连接bluetoothGatt.disconnect()
不要和bluetoothGatt.close()一起调用,容易出现无法触发断连状态回调(onConnectionStateChange),gatt对象的保存也要注意,最好一一对应,否则容易出现连接和断连不完全等问题。
7、扫描回调OnScanResult()方法
回调中不要处理太多的逻辑,尽早结束回调,不然蓝牙资源利用频繁容易卡死主线程。
8、息屏后保持扫描不停止
需要设置过滤filters,可以设一个空列表
- List<ScanFilter> filters = new ArrayList<>();
- filters.add(new ScanFilter.Builder().setServiceUuid(mUuid).build());
- bleScanner.startScan(scanFilters, scanSettings, scanCallback);
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。