Bluetooth---Android蓝牙4.0的数据通讯

来源:互联网 发布:咖喱粉什么牌子好 知乎 编辑:程序博客网 时间:2024/05/16 07:32
1.检测手机是否支持蓝牙4.0(一般手机4.3以上的android系统都支持)

   

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <span style="font-size:14px;"if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {  
  2.               showMsg(R.string.ble_not_supported);  
  3.              finish();  
  4.          }</span>  
   2.检测蓝牙是否打开,提示用户打开蓝牙(在此之前需要加相应的权限)
      添加权限:
[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <span style="font-size:14px;">    <uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>  
  2.     <uses-permission android:name="android.permission.BLUETOOTH"/>  
  3.     <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/></span>  

       获取蓝牙适配器

        

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1.    <span style="font-size:14px;">final BluetoothManager bluetoothManager =  
  2.                  (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);  
  3.          bluetoothAdapter = bluetoothManager.getAdapter();  
  4.    如果蓝牙处于关闭状态,则通过下面代码提示用户启动蓝牙:  
  5.       
  6.  Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);  
  7.                     startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);  
  8.   
  9. </span>  
      3.启动关闭蓝牙,获取蓝牙状态
          

           判断蓝牙状态:bluetoothAdapter.isEnabled()

           开启蓝牙:bluetoothAdapter.enable();

           关闭蓝牙:bluetoothAdapter.disable();

      

      4.蓝牙启动后,就该搜索设备了

           

           开启搜索: bluetoothAdapter.startLeScan(mLeScanCallback);

           停止搜索: bluetoothAdapter.stopLeScan(mLeScanCallback);

           搜索回调:

                     

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1.   private BluetoothAdapter.LeScanCallback mLeScanCallback =  
  2.     new BluetoothAdapter.LeScanCallback() {  
  3.   
  4.   @Override  
  5.  public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {  
  6.     runOnUiThread(new Runnable() {  
  7.         @Override  
  8.         public void run() {  
  9.           //在这里将搜到的设备显示到界面  
  10.         }  
  11.     });  
  12. }  
          

        5.建立连接

         

           

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1.  public boolean connect(BluetoothDevice  device ) {  
  2. if (device == null) {  
  3.     Log.w(TAG, "Device not found.  Unable to connect.");  
  4.     return false;  
  5. }  
  6. mBluetoothGatt = device.connectGatt(thisfalse, mGattCallback);  
  7. return true;  
                       
              连接时需要注册一个回调接口:
[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1.  private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {  
  2.       //检测连接状态变化  
  3.                @Override  
  4.       public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {  
  5.           
  6.           if (newState == BluetoothProfile.STATE_CONNECTED) {  
  7.                
  8.           } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {  
  9.                 
  10.           }  
  11.       }  
  12.   
  13.       @Override  
  14.       public void onServicesDiscovered(BluetoothGatt gatt, int status) {  
  15.            
  16.       }  
  17.   
  18.       @Override  
  19.       public void onCharacteristicRead(BluetoothGatt gatt,  
  20.                                        BluetoothGattCharacteristic characteristic,  
  21.                                        int status) {  
  22.            
  23.       }  
  24.                //接收蓝牙回传数据  
  25.       @Override  
  26.       public void onCharacteristicChanged(BluetoothGatt gatt,  
  27.                                           BluetoothGattCharacteristic characteristic) {  
  28.         System.out.println("接收数据");  
  29.         byte[] data=characteristic.getValue();  
  30.           
  31.       }  
  32.                    //检测用户向蓝牙写数据的状态  
  33. @Override  
  34. public void onCharacteristicWrite(BluetoothGatt gatt,  
  35.         BluetoothGattCharacteristic characteristic, int status) {  
  36.     Log.e(TAG, "write status"+":"+status);  
  37.     if(status==BluetoothGatt.GATT_SUCCESS){  
  38.         System.out.println("--------write success----- status:");  
  39.     }  
  40.     super.onCharacteristicWrite(gatt, characteristic, status);  
  41. }  
  42.         
  43.   };  
       断开连接:

               mBluetoothGatt.disconnect();

 6.发送数据

     //设置特性数据回传通知

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,  
  2.                                              boolean enabled) {  
  3.        if (mBluetoothAdapter == null || mBluetoothGatt == null) {  
  4.            Log.w(TAG, "BluetoothAdapter not initialized");  
  5.            return;  
  6.        }  
  7.        if (mBluetoothGatt.setCharacteristicNotification(characteristic, enabled)) {  
  8.            BluetoothGattDescriptor descriptor = characteristic.getDescriptor(  
  9.                    UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));  
  10.            descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);  
  11.            mBluetoothGatt.writeDescriptor(descriptor);  
  12.        }  
  13.    }  
  14.   
  15.     
  16.    /** 
  17.     * 向设备发送数据 
  18.     * @param serviceUuid 
  19.     * @param characterUuid 
  20.     * @param notifactionUuid 
  21.     * @param data 
  22.     */  
  23.    public void writeDataToDevice(byte[] data){  
  24.     if (mBluetoothGatt == null) {  
  25.         return;  
  26.     }  
  27.     BluetoothGattService bluetoothGattService = mBluetoothGatt  
  28.             .getService(UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb"));//蓝牙设备中需要使用的服务的UUID  
  29.     if (bluetoothGattService == null) {  
  30.         Log.e(TAG, "service:"+mBluetoothGatt.getServices().size());  
  31.         Log.e(TAG, "service not found!");  
  32.         return;  
  33.     }  
  34.     BluetoothGattCharacteristic mCharac = bluetoothGattService  
  35.             .getCharacteristic("0000fff6-0000-1000-8000-00805f9b34fb");//需要使用该服务下具体某个特性的UUID  
  36.     if (mCharac == null) {  
  37.         Log.e(TAG, "HEART RATE Copntrol Point charateristic not found!");  
  38.         return;  
  39.     }  
  40.     BluetoothGattCharacteristic nCharacteristic=bluetoothGattService.getCharacteristic("0000fff7-0000-1000-8000-00805f9b34fb");//蓝牙模块向手机端回传特性UUID  
  41.     setCharacteristicNotification(nCharacteristic, true);  
  42.     Log.e(TAG, "data:"+Arrays.toString(data));  
  43.     mCharac.setValue(data); //设置需要发送的数据  
  44.     try {  
  45.         Thread.sleep(500);  
  46.     } catch (InterruptedException e) {  
  47.         e.printStackTrace();  
  48.     }  
  49.     writeCharacteristic(mCharac);  
  50.    }  
  51.      
  52.    public void writeCharacteristic(BluetoothGattCharacteristic characteristic) {  
  53.   
  54.     if (mBluetoothAdapter == null || mBluetoothGatt == null) {  
  55.         Log.e(TAG, "BluetoothAdapter not initialized");  
  56.         return;  
  57.     }  
  58.     boolean result=mBluetoothGatt.writeCharacteristic(characteristic);//开始写入数据  
  59.         if(result){  
  60.           Log.e(TAG, "write success!");  
  61.         }else {  
  62.     Log.e(TAG, "write fail!");  
  63. }  
  64. }  
  65.     
1 0