Android蓝牙开发

1.初始化

mBLEService = new BluetoothLeService(this); //区别于android的四大组件服务,相当于工具类BLECommunicateUtils.setBLEService(mBLEService);mBLEService.setOnServiceDiscoverListener(mOnServiceDiscover);mBLEService.setOnDataAvailableListener(mOnDataAvailable);mBLEService.setOnDisconnectListener(mOnDisconnectListener);mBLEService.setOnConnectListener(mOnConnectListener);

2.扫描获取设备

/** * @param enable (扫描使能,true:扫描开始,false:扫描停止) * @return void * @throws * @Title: scanLeDevice * @Description: TODO(扫描蓝牙设备) */private void scanLeDevice(final boolean enable) {    if (enable) {        // Stops scanning after a pre-defined scan period.        mHandler.postDelayed(new Runnable() {            @Override            public void run() {                mScanning = false;                mBluetoothAdapter.stopLeScan(mLeScanCallback);                if (mBLEService != null) {                    mBLEService.close();                }                Log.e(TAG, "扫描时间结束,停止扫描");            }        }, SCAN_PERIOD);        /* 开始扫描蓝牙设备,带mLeScanCallback 回调函数 */        mScanning = true;        mBluetoothAdapter.startLeScan(mLeScanCallback);        Log.e(TAG, "开始扫描");    } else {        mScanning = false;        mBluetoothAdapter.stopLeScan(mLeScanCallback);        Log.e(TAG, "停止扫描");    }}

3.扫描蓝牙的回调

/** * 蓝牙扫描回调函数 实现扫描蓝牙设备,回调蓝牙BluetoothDevice,可以获取name MAC等信息 **/private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {    @Override    public void onLeScan(final BluetoothDevice device, final int rssi,                         byte[] scanRecord) {        if (device.getName() != null && device.getName().equals(BLUETOOTH_NAME)) {            Log.e(TAG, "扫描得到我的设备");            if (mScanning) {                mBluetoothAdapter.stopLeScan(mLeScanCallback);                mScanning = false;            }            mBLEService.connect(device);        }    }};

4.连接蓝牙的回调BluetoothGattCallback

/** * connect a remoteDevice callback */private BluetoothGattCallback mGattCallBack = new BluetoothGattCallback() {    //建立连接    @Override    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {        super.onConnectionStateChange(gatt, status, newState);        if (newState == BluetoothProfile.STATE_CONNECTED) {            mBluetoothGatt.discoverServices();            if (mOnConnectListener != null) {                mOnConnectListener.onConnect(mBluetoothGatt);            }        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {            // 2016/4/25 if disconnect ,trigger mOnDisconnectListener            if (mOnDisconnectListener != null) {                mOnDisconnectListener.onDisconnect(mBluetoothGatt);            }        }    }    //发现服务    @Override    public void onServicesDiscovered(BluetoothGatt gatt, int status) {        super.onServicesDiscovered(gatt, status);        if (status == BluetoothGatt.GATT_SUCCESS && mOnServiceDiscoverListener != null) {            mOnServiceDiscoverListener.onServiceDiscover(gatt);        }    }    @Override    public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {        super.onCharacteristicRead(gatt, characteristic, status);        if (status==BluetoothGatt.GATT_SUCCESS && mOnDataAvailableListener != null) {            mOnDataAvailableListener.onCharacteristicRead(gatt, characteristic);        }    }    @Override    public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {        super.onCharacteristicWrite(gatt, characteristic, status);        if (mOnDataAvailableListener != null) {            mOnDataAvailableListener.onCharacteristicWrite(gatt,                    characteristic);        }    }    @Override    public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {        super.onCharacteristicChanged(gatt, characteristic);        if (mOnDataAvailableListener != null) {            mOnDataAvailableListener.onCharacteristicWrite(gatt,                    characteristic);            mOnDataAvailableListener.onCharacteristicRead(gatt,characteristic);        }    }    /* * 读描述值 * */    @Override    public void onDescriptorRead(BluetoothGatt gatt,                                 BluetoothGattDescriptor descriptor, int status) {        super.onDescriptorRead(gatt, descriptor, status);    }    /* * 写描述值 * */    @Override    public void onDescriptorWrite(BluetoothGatt gatt,                                  BluetoothGattDescriptor descriptor, int status) {        super.onDescriptorWrite(gatt, descriptor, status);    }    @Override    public void onReliableWriteCompleted(BluetoothGatt gatt, int status) {        super.onReliableWriteCompleted(gatt, status);    }    @Override    public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {        super.onReadRemoteRssi(gatt, rssi, status);    }    @Override    public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {        super.onMtuChanged(gatt, mtu, status);    }};

5.在onServicesDiscovered的回调中发送指令

/** * get the supported characteristics , maybe need to change * * @param gattServices gattServices */private void displayGattServices(List<BluetoothGattService> gattServices) {    if (gattServices == null) {        return;    }    for (BluetoothGattService gattService : gattServices) {        List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();        for (final BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {            if (gattCharacteristic.getUuid().toString().equals(HEART_RATE_MEASUREMENT)) {                // 接受Characteristic被写的通知,收到蓝牙模块的数据后会触发mOnDataAvailable.onCharacteristicWrite()                mBLEService.setCharacteristicNotification(                        gattCharacteristic, true);            }            gattCharacteristic_charA = gattCharacteristic;        }    }    BLECommunicateUtils.sendData(gattCharacteristic_charA, StringUtils.            hexStringToBytes("***************指令代码*****************"));}

5.接收蓝牙设备返回的数据

需要设置

// 接受Characteristic被写的通知,收到蓝牙模块的数据后会触发mOnDataAvailable.onCharacteristicWrite()mBLEService.setCharacteristicNotification(        gattCharacteristic, true);

在连接蓝牙 的onCharacteristicChanged回调中处理接收的数据

@Overridepublic void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {    Log.e(TAG, "收到了数据" + characteristic.toString());    //断开连接    if (mBLEService != null) {        mBLEService.close();    }    Log.e(TAG, "断开连接");}

6.注意事项:

  • 关闭蓝牙
  /** * close the BluetoothGatt */    public void close() {        if (mBluetoothGatt == null) {            return;        }        mBluetoothGatt.close();// mBluetoothGatt = null; 要设置不要置为null因为安卓mBluetoothGatt有一个限制,连接几次后发现连不上的情况.    }

7.Demo参考:
http://download.csdn.net/detail/github_34224676/9793523
Github传送门:
https://github.com/IOXusu/Android-BLE-Demo

更多相关文章

  1. android adb shell 命令大全
  2. android adb shell 命令大全
  3. android系统学习笔记二
  4. android之蓝牙操作(二)
  5. 通过JS或PHP检测Android
  6. Android判断当前的android设备是否处于联网状态
  7. Android常用权限
  8. Android(安卓)获取手机唯一标识(仅限IMEI)
  9. android:screenOrientation的说明

随机推荐

  1. AndroidStudio使用(一):快捷键(windows|mac)及
  2. android 4.4 电池电量显示分析(低电量提醒
  3. 在源码中编译自己的Android project
  4. Android(安卓)语言切换(eclipse)
  5. Android Application的作用
  6. Android(安卓)获取SIM卡运营商
  7. android-viewbadger为你的Android(安卓)a
  8. RxJava简明教程
  9. Android 6.0 新特性(官方文档翻译)
  10. android中使用像css一样的样式