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 gattServices) {    if (gattServices == null) {        return;    }    for (BluetoothGattService gattService : gattServices) {        List 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(安卓)仿360恶意广告拦截扫描
  2. android蓝牙开发入门到精通3---服务端客户端通信
  3. Android(安卓)获取设备各种信息
  4. android 获取手机设备信息
  5. Android(安卓)SDK自带教程之BluetoothChat
  6. Android获取设备信息(利用反射)
  7. Android(安卓)监听耳机外放设备
  8. 判断Android设备是否连接网络
  9. Android(安卓)蓝牙配对、连接和通信

随机推荐

  1. 记录一下maven android 的启动命令
  2. GooglePlay 分包 安装obb
  3. android RelativeLayout 相对布局
  4. Android各个版本API的区别
  5. Android(安卓)3.0上访问出现 android.os.
  6. android repo/git server 建立过程(2)
  7. Android下使用Properties文件保存程序设
  8. 详解四种基本布局 (layout)
  9. Android中自定义View仿京东秒杀倒计时
  10. Android:adb shell am命令行发送Activity