Android ble 4.0相关知识总结

一、设备要求

1.Android 4.3(SDK VERSION >= 18),4.3的android手机只能作为主机设备,而不能作为外围设备。

2.android 5.0 支持主机也支持外围设备

 <uses-sdk
        android:minSdkVersion="18"
        android:targetSdkVersion="19" />


二、开发的时候需要添加的权限

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

三、利用api判断android手机是否支持ble

if(getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE )) {
    Toast.makeText(getActivity(), "支持", Toast.LENGTH_SHORT).show();
}else{
    Toast.makeText(getActivity(), "不支持", Toast.LENGTH_SHORT).show();
}


四、开启蓝牙
   // 初始化 Bluetoothadapter, 通过蓝牙管理器得到一个参考蓝牙适配器(API必须在以上android4.3或以上和版本)
   BluetoothManager   bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
   BluetoothAdapter  bluetoothAdapter = bluetoothManager.getAdapter();
 
  //如果蓝牙未开启就开启蓝牙
  if (!bluetoothAdapter.isEnabled()) {
                   bluetoothAdapter.enable();
 }

五、开始搜索BLE设备
<span style="font-size:10px;">bluetoothAdapter.startLeScan(leScanCallback); //其中leScanCallback为扫描的回调接口
定义如下所示
LeScanCakkback leScanCallback = new BluetoothAdapter.LeScanCallback() {
            @Override
            public void onLeScan( BluetoothDevice bluetoothDevice, int i, byte[] bytes) {
                    // do something
            }
        };</span>

 
 
 
 回调函数onLeScan()中的三个参数分别为device:蓝牙设备,rssi:设备返回的接收信号强度, scanRecord:设备广播消息 
六、绑定BLE设备以及解除绑定BLE设备
1.绑定BLE设备
    /**
     * 绑定BLE设备
     */
    public static Boolean bondDevice(BluetoothDevice bluetoothDevice) {
        Boolean returnValue;
        try {
            Class class1 = Class.forName("android.bluetooth.BluetoothDevice");
            Method createBondMethod = class1.getMethod("createBond");
            returnValue = (Boolean) createBondMethod.invoke(bluetoothDevice);
        } catch (Exception e) {
            returnValue = false;
        }
        return returnValue;
    }
2.解除绑定BLE设备
    /**
     * 解除绑定
     * @param bluetoothDevice
     * @return
     */
    public static Boolean unBondDevice(BluetoothDevice bluetoothDevice) {
        boolean returnValue;
        try {
            Method m = bluetoothDevice.getClass().getMethod("removeBond");
            returnValue = (Boolean) m.invoke(bluetoothDevice);
        } catch (Exception e) {
            returnValue = false;
        }
        return returnValue;
    }

七、连接BLE设备,连接成功后的到相关的service以及 characteristic
    /**
     * 连接BLE设备
     *
     * @param bluetoothDevice
     * @return
     */
    public boolean connect(final BluetoothDevice bluetoothDevice) {
        if (bluetoothDevice == null) {
            return false;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                bluetoothDevice.connectGatt(BluetoothLEService.this, true, new BluetoothGattCallback() {  //BluetoothGattCallback 为回调接口

                    @Override
                    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { //该函数为连接状态改变的函数
                        if (newState == BluetoothProfile.STATE_CONNECTED) {
                            Log.d(TAG, "连接成功");
                            Log.d(TAG, "开始搜索服务:");
                            gatt.discoverServices() ;                 //连接成功之后就可以开始搜索服务
                        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                            close(gatt);
                            Log.d(TAG, "断开连接.");
                        } else {
                            Log.d(TAG, "连接失败" + newState);
                        }
                    }

                    @Override
                    public void onServicesDiscovered(final BluetoothGatt gatt, int status) {       //发现服务的回调函数
                        if (status == BluetoothGatt.GATT_SUCCESS) {           
                            // 根据uuid得到读服务
                            BluetoothGattService readService = gatt.getService(UUID.fromString("0000ffe0-0000-1000-8000-00805f9b34fb")); 
                            if (null != readService) {      
                            BluetoothGattCharacteristic readCharacteristic = readService.getCharacteristic(UUID.fromString("0000ffe4-0000-1000-8000-00805f9b34fb"))
                             if (null != readCharacteristic) {
                                    //是否接收通知,收到的通知会通过onCharacteristicChanged回调函数返回
                                    gatt.setCharacteristicNotification(readCharacteristic, true);   
                                    gatt.readCharacteristic(readCharacteristic);  // 读取数据,读取的结果通过onCharacteristicRead回调返回。
                                }
                            }
                            //得到写操作的服务以及写操作的特征值
                         BluetoothGattService   writeService = gatt.getService(UUID.fromString("0000ffe5-0000-1000-8000-00805f9b34fb")); 
                            if (null != writeService) {
                            //再得到特征值                                
                            BluetoothGattCharacteristic writeCharaceristic = writeService.getCharacteristic(UUID.fromString("0000ffe9-0000-1000-8000-00805f9b34fb"));
                            }

                        } else {
                            Log.d(TAG, "发现服务的状态: " + status);
                        }
                    }

                    @Override
                    public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { //读取数据的结果会通过这个回调函数返回来
                        if (status == BluetoothGatt.GATT_SUCCESS) {
                            byte[] value = characteristic.getValue();      // 得到数据
                            analyticFrame(value,gatt,bluetoothDevice);     //这是我自己程序中定义的解析数据的方法,
                        } else {
                            Log.d(TAG, "发现特征值的状态" + status);
                        }
                    }

                     //特征值状态改变的回调函数
                    @Override
                    public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { 
                        byte[] value = characteristic.getValue(); //得到数据
                        analyticFrame(value,gatt,bluetoothDevice);//这是我自己程序中定义的解析数据的方法,

                    }

                    @Override
                    public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { //写操作成功与否的回调函数
                        super.onCharacteristicWrite(gatt, characteristic, status);
                        if (status == BluetoothGatt.GATT_SUCCESS) {
                            Log.d("TAG", "写成功");
                        }
                    }
                });
            }
        }).start();
        return true;
    }

接口中有9个方法可以重写,这里只重写了几个常用的方法。

八、断开连接
/**
 * 断开连接
 */
public void disconnect() {
 if (mBluetoothAdapter == null || mBluetoothGatt == null) {
    Log.w(TAG, "BluetoothAdapter not initialized");
    return;
  }
  mBluetoothGatt.disconnect();
 }

九、释放资源
    /**
     * 释放资源
     */
    public void close(BluetoothGatt mBluetoothGatt) {
        if (mBluetoothGatt == null) {
            return;
        }
        mBluetoothGatt.close();
        mBluetoothGatt = null;
    }










评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值