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原生SQLite数据库的使用
  2. android之蓝牙操作(二)
  3. 【Android游戏开发二十一】Android os设备谎言分辨率的解决方案!
  4. android 应用程序数据共享shareuserid篇+ContentResolver+Conten
  5. ArcGIS for Android 离线数据编辑原理
  6. android 多媒体数据库详解

随机推荐

  1. unity与android的无缝连接
  2. Android:Task概念以及相关
  3. 尚硅谷15天Android基础笔记
  4. Android 实现ListView 3D效果 - 2 - 弹性
  5. Android(安卓)数据库SQLiteDatabase的使
  6. Google Android真实的谎言
  7. [Android] Android进程与线程基本知识
  8. Android布局优化(五)绘制优化—避免过度绘
  9. 【Android】1:Android APP开发入门篇
  10. QtAndroid详解(3):startActivity实战Andro