蓝牙API介绍及基本功能实现

ONE,传统蓝牙

  • BluetoothAdapter:本地蓝牙设备适配器,用于管理蓝牙的开启/关闭、重命名、扫描、配对、连接
  • BluetoothClass:蓝牙设备类,用于描述蓝牙设备类型
  • BluetoothDevice:远程蓝牙设备类
  • BluetoothSocket:与tcpSocket类似,进行蓝牙连接
  • BluetoothServerSocket:与tcpServerSocket类似,等待连接


获取本地蓝牙适配器

BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();

打开/关闭本地蓝牙

adapter.enable();//打开蓝牙
adapter.disable();//关闭蓝牙
adapter.isEnabled();//蓝牙是否处于开启状态
adapter.getState();//获取本机蓝牙状态 

通过监听BluetoothAdapter.ACTION_STATE_CHANGED监听蓝牙状态的改变


蓝牙重命名/获取本机蓝牙名

mAdapter.setName(name);//本地蓝牙重命名
mAdapter.getName();//获取本机蓝牙名

通过监听BluetoothAdpater.ACTION_LOCAL_NAME_CHANGED监听本机蓝牙名称的改变


蓝牙可检测性设置

有两种方案,

首先第一种实现,简单但对可检测时间有限制

Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
		//默认可检测时间为120秒,调用该方法最高可设置300秒
		intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
		startActivity(intent);


第二种实现方案,就是Android源码中的实现方案,可以任意规定可检测时长,甚至永不超时均可(参考Android4.42源码)

/**
*mode有三种取值
*BluetoothAdapter.SCAN_MODE_CONNECTABLE:对已配对设备可见,具有扫描功能
*BluetoothAdapter.SCAN_MODE_NONE:对所有设备不可见,不具有扫描功能
*BluetoothAdapter.SCAN_MODE_CONNECTABLE_*DISCOVERABLE:对所有设备可见,具有扫描功能
*duration为扫描时长
*/

mAdapter.setScanMode(mode, duration);
//设置alarm,当timeout结束时就关闭蓝牙的可检测性
BluetoothDiscoverableTimeoutReceiver.setDiscoverableAlarm(mContext, endTimestamp);
这是源码中的实现方案,但是BluetoothAdapter.setScanMode()没有办法去调用,只能利用反射

获取已配对设备列表

List<BluetoothDevice> list = (List<BluetoothDevice>) adapter.getBondedDevices();

开启扫描/关闭扫描

adapter.startDiscovery();//开启蓝牙扫描功能
adapter.cancelDiscovery();//关闭蓝牙扫描功能

在扫描到设备时系统会发送BluetoothDevice.ACTION_FOUND的广播,通过监听该广播可以获取到设备信息

获取到设备后调用如下方式进行连接

BluetoothSocket _BluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);

获取到socket后可以获取到输入输出流,这里的uuid可以在网页的uuid生成器在线生成,remotedevice和本机蓝牙设备的uuid必须相同


TWO,BLE低功耗蓝牙

获取蓝牙适配器的步骤同上,扫描ble设备的方法如下:

//开启蓝牙扫描
mBluetoothAdapter.startLeScan(mLeScanCallback);
//结束蓝牙扫描
mBluetoothAdapter.stopLeScan(mLeScanCallback);

其中mlLeScanCallback为BluetoothAdapter.LeScanCallback对象,

private BluetoothAdapter.LeScanCallback mLeScanCallback =
            new BluetoothAdapter.LeScanCallback() {

        @Override
        public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
                       。。。
                   //扫描到设备后回调
}


扫描到设备后可以进行连接,方法如下

mBluetoothGatt = mBluetoothDevice.connectGatt(BluetoothCODAService.this, false, mGattCallback);

其中mGattCallback为BluetoothGattCallback对象

 private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {

			if(newState == BluetoothProfile.STATE_CONNECTED){
	        //连接成功回调
		
			}else if(newState == BluetoothProfile.STATE_DISCONNECTED){
               //连接失败回调
                      }
          public void onServicesDiscovered(BluetoothGatt gatt, int status) {
                   
            if (status == BluetoothGatt.GATT_SUCCESS) { // 0
                                         //搜索到服务回调

      } else {
    //未搜索到服务回调
            }
        }

        @Override
        // Result of a characteristic read operation
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                //接收到数据回调
            }
        }

         @Override
         public void onCharacteristicWrite(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic, int status) {
          //发送数据回调
         }
    
        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
          
        }

        @Override
            public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor,
                                 int status) {
        }

        @Override
        public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor,
                                      int status) {
        }    

        @Override
        public void onReliableWriteCompleted(BluetoothGatt gatt, int status) {
        
           }
    };

 }


           


连接成功后如果要进行通信还必须搜索服务

mBluetoothGatt.discoverServices();

搜索服务后会回调onServicesDiscovered方法。

至此,就可以进行读写数据了

//读数据
mBluetoothGatt.readCharacteristic(characteristic);
//写数据
 mBluetoothGatt.writeCharacteristic(characteristic,value);

关于低功耗蓝牙的理论知识可以参考 Android蓝牙BLE低功耗相关简单总结




你可能感兴趣的:(蓝牙通信,BLE,低功耗蓝牙,蓝牙连接,传统蓝牙)