Android BLE 4.0 蓝牙开发流程与详解

2016-12-26  本文已影响0人  I呀IT小胖

简介
<blockquote>Android 4.3 (API18)引入支持BLE的central角色,提供包括API来发现 搜索,链接BLE设备,与传统蓝牙 (ClassicBluetooth)不同,BLE更加低功耗。
</blockquote>
BLE详解

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
- Android M(6.0)需要添加定位权限(动态判断)
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

<blockquote>这里是个坑,因为没有定位权限,根本不能扫描,而小米手机的权限系统被小米改了,定位权限根本拿不到拒绝的回调.弹出询问用户是否同意使用权限时,点了拒绝,小米的定位权限里也认为是同意了此全新,拿不到拒绝权限的回调,也就无法对用户拒绝时做出合理操作.我的做法是,判断是否是小米手机,如果是,则在扫描之前先弹出一个dialog提示框 ,提示用户一定要同意定位权限,不然这个app所有功能将使用不了

// 检查当前手机是否支持ble 蓝牙,如果不支持退出程序
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) 
{  
 // 广播 或者eventBus 发出通知 做出不支持蓝牙的通知
}
private void scanLeDevice(final boolean enable) {   
// 如果当前是没有扫描状态,开始扫描
if (enable) {   
          //定位权限申请
          PermissionUtils.askLocationInfo(this,new PermissionUtils.PermissionListener() {        
             @Override       
               public void onGranted() {        
            //权限申请成功
                  //首先先发送延迟消息, SCAN_PERIOD=10000后停止扫描设备
                    handler.postDelayed(new Runnable() {       
                      @Override            
                       public void run() {             
                            scanning = false;               
                             // 停止扫描设备         
                           bleService.scanLeDevice(!enable);         
                      }          
                    } ,SCAN_PERIOD);      
                
                       scanning = true;      
                      // 开始扫描设备   leScanCallback 扫描设备的回调
                    bluetoothAdapter.startLeScan(leScanCallback);
   }        
                       @Override        
                     public void onDenied(String[] permissions, String permissionDesc, boolean isCancle, int requestCode) {     
                      // 权限申请失败, 弹出申请失败的提示框,提醒用户需要定位权限
              }                                      
 });  
              } else {   
                      // 如果当前处于扫描状态,停止扫描
                         scanning = false;  
                      // 停止扫描设备 
                     bluetoothAdapter.stopLeScan(leScanCallback);
           
        }   
     }
  }
//设备扫描回调
private BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() {
           @Override  
           public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
            // BluetoothDevice  BLE设备的对象 说明发现了设备, 来到这里就需要使用设备连接GATT Server 连接上之后就可以作出获取数据和传输数据的操作.
            }
}
//设备连接成功后的回调
private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() { 
      @Override  
      // 连接设备状态的改变
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {    

            if (newState == BluetoothProfile.STATE_CONNECTED) {    
              // 连上了新的设备
              } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {   
               // 设备断开
              gatt.close();    
          }  
     }  
       @Override  
    // 发现了新的设备
         public void onServicesDiscovered(BluetoothGatt gatt, int status) { 
             if (status == BluetoothGatt.GATT_SUCCESS) {   
          //    发现新的设备,订阅Characteristic的值是否有改变,如果有改变则做出相应的处理
           // enableNotification(gatt, ServerUUID, 订阅的Characteristic的UUID) 视情况是否要实时监听某一种数据而决定是否订阅
            BluetoothGattService service = getService(ServerUUID, gatt);    
            BluetoothGattCharacteristic readChar = getCharacteristic(CharacteristicUUID, BluetoothGattService);
            gatt.setCharacteristicNotification(readChar, true);
            //返回一个boolean 表示是否订阅成功
         }  
       }  
         @Override 
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic,   int status) {         
            // 主动读取 Characteristic  里面的数据  ,来到这里则可以解析需要的数据了
               if (status == BluetoothGatt.GATT_SUCCESS) {  
           }   
}   
          @Override  
         public void onCharacteristicChanged(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic)    {            
                      //当Characteristic里面的数据发生改变的时候 走这个回调方法 也就是onServicesDiscovered在订阅Characteristic的监听 
                      // 比如一些需要实时知道的数据,气温,心跳等等
}};
**注意**

<blockquote>由于我这个工程的数据只存在Characteristic当中并且只关注 Characteristic当中的数据是否有发生变化,并没有关注Characteristic的Descriptor 的数据,如果开发同学需要用到Descriptor 当中的数据 BluetoothGattCallback 方法当中也有相应的回调,也有相应的订阅的监听数据变化的方法.</blockquote>

最后
<blockquote> 当以上操作遇到任何一种异常时,必须要停止蓝牙的连接,以免造成ARM
开发流程相对简单.也是之前学习的时候收获的一些东西,花点时间分享出来,希望可以给予开发同学一些帮助,由于各个开发项目的不同的情况太多,这里也没有给出相应的代码,只是说明了一下流程和概念.下一篇写一下解析数据,和BLE空中升级.</blockquote>

上一篇 下一篇

猜你喜欢

热点阅读