Android Ble基础操作

  • 初始化工作
  • 蓝牙扫描、停止扫描
  • 蓝牙连接
  • 绑定、移除设备
  • 链接

初始化工作

RxBleClient rxBleClient = RxBleClient.create(context);//打开蓝牙//Intent enableBtIntent = new //Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);//int REQUEST_ENABLE_BT = 1;//context.startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);

蓝牙扫描、停止扫描

public void stopScan() {new Thread(new Runnable() {@SuppressWarnings({ "deprecation" })@Overridepublic void run() {BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();Log.i(TAG, "stopScan-bt--isEnabled:" + adapter.isEnabled());if (!adapter.isEnabled()) {adapter.enable();}adapter.stopLeScan(leScanCallback);}}).start();}public void startScan() {Log.d(TAG, "startScan in");new Thread(new Runnable() {@SuppressWarnings("deprecation")@Overridepublic void run() {// TODO Auto-generated method stubBluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();Log.i(TAG, "startScan-bt--isEnabled:" + adapter.isEnabled());if (!adapter.isEnabled()) {adapter.enable();}while (!adapter.startLeScan(leScanCallback)) {}}}).start();}private LeScanCallback leScanCallback = new LeScanCallback() {@Overridepublic void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {Log.d(TAG, "onLeScan--isConnected() is " + isConnected()+ "\n device.getName() is " + device.getName());};

蓝牙连接

private void receive(String mac) {bleDevice = rxBleClient.getBleDevice(mac);createBound(bleDevice.getBluetoothDevice());bleDevice.observeConnectionStateChanges()//监听蓝牙连接状态// .compose(bindUntilEvent(DESTROY)).observeOn(AndroidSchedulers.mainThread())// .subscribe();.subscribe(new Consumer<RxBleConnection.RxBleConnectionState>() {@Overridepublic void accept(RxBleConnection.RxBleConnectionState newState)throws Exception {Log.i(TAG,"ConnectionStateChanges:"+ newState.name());if (newState == RxBleConnectionState.DISCONNECTED) {startScan();} else if (newState == RxBleConnectionState.CONNECTED) {stopScan();}}});connectionDisposable = bleDevice.establishConnection(true)// .compose(bindUntilEvent(DESTROY)).observeOn(AndroidSchedulers.mainThread()).doFinally(new Action() {@Overridepublic void run() throws Exception {connectionDisposable.dispose();connectionDisposable = null;}}).subscribe(new Consumer<RxBleConnection>() {@Overridepublic void accept(RxBleConnection connection)throws Exception {onConnectionReceived(connection);}}, new Consumer<Throwable>() {@Overridepublic void accept(Throwable t) throws Exception {Log.i(TAG, "connect-Exception:" + t.getMessage());}});}

绑定、移除设备

private void createBound(BluetoothDevice device) {if (null == device)return;int bondsState = device.getBondState();if (bondsState == BluetoothDevice.BOND_NONE) {try {Method m = device.getClass().getMethod("createBond",(Class[]) null);m.invoke(device, (Object[]) null);} catch (Exception e) {e.printStackTrace();}}}private void removeBound(BluetoothDevice device) {if (null == device)return;int bondsState = device.getBondState();if (bondsState == BluetoothDevice.BOND_BONDED) {try {Method m = device.getClass().getMethod("removeBond",(Class[]) null);m.invoke(device, (Object[]) null);} catch (Exception e) {e.printStackTrace();}}}

private void onConnectionReceived(RxBleConnection connection) {// noinspection ConstantConditionsLog.i(TAG, "onConnectionReceived:" + connection);this.rxBleConnection = connection;onNotify();}public void onNotify() {Log.i(TAG, "onNotify:");if (isConnected()) {rxBleConnection.setupNotification(/*UUID*/).flatMap(new Function<ObservableSource<byte[]>, ObservableSource<byte[]>>() {@Overridepublic ObservableSource<byte[]> apply(@NonNull ObservableSource<byte[]> arg0)throws Exception {return arg0;}}).observeOn(Schedulers.io()).subscribe(new Consumer<byte[]>() {@Overridepublic void accept(byte[] arg0) throws Exception {//onNotificationReceived(arg0);}}, new Consumer<Throwable>() {@Overridepublic void accept(Throwable arg0) throws Exception {// onNotificationSetupFailure();Log.i(TAG,"received-Exception:" + arg0.getMessage());}});rxBleConnection.setupNotification(/*UUID*/).flatMap(new Function<ObservableSource<byte[]>, ObservableSource<byte[]>>() {@Overridepublic ObservableSource<byte[]> apply(@NonNull ObservableSource<byte[]> arg0)throws Exception {return arg0;}}).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<byte[]>() {@Overridepublic void accept(byte[] arg0) throws Exception {//onNotificationReceivedControl(arg0);//收到蓝牙设备发送信息}}, new Consumer<Throwable>() {@Overridepublic void accept(Throwable arg0) throws Exception {// onNotificationSetupFailure();Log.i(TAG, "control-Exception:" + arg0.getMessage());}});}}

private void onWriteFtc(byte[] data) {Log.d(TAG, "onWriteFtc data is " + new String(data)+ "and isconnected is" + isConnected());if (isConnected()) {rxBleConnection.writeCharacteristic(/*UUID*/, data).observeOn(Schedulers.io()).subscribe(new Consumer<byte[]>() {@Overridepublic void accept(byte[] arg0) throws Exception {// TODO Auto-generated method stub//String str = HexString.bytesToHex(arg0);//Log.d(TAG, "onWriteFtcSuccess:" + str);}}, new Consumer<Throwable>() {@Overridepublic void accept(Throwable arg0) throws Exception {// TODO Auto-generated method stubLog.d(TAG, "onWriteFailure:" + arg0.getMessage());}});}}

链接

RxAndroidBle工具包.
RxAndroidBle更多明细.

更多相关文章

  1. 用Javascript判断访问来源操作系统, 设备, 浏览器类型
  2. android获取设备存储信息
  3. 第二部分:开发简要指南-第五章 支持不同的Android设备
  4. Android设备与USB设备的连接通讯
  5. Android设备到底侵犯了微软的什么专利
  6. Android设备的唯一ID
  7. Android TV蓝牙模块

随机推荐

  1. Mysql指定日期区间的提取方法
  2. mysql 8.0.11 macos10.13安装配置方法图
  3. mysql 5.6.23 安装配置环境变量教程
  4. Ubuntu16.04安装mysql5.7.22的图文教程
  5. 浅析mysql.data.dll驱动各版本介绍
  6. Mysql数据库实现多字段过滤的方法
  7. MySQL入门(五) MySQL中的索引详讲
  8. MySQL入门(四) 数据表的数据插入、更新、
  9. MySQL入门(三) 数据库表的查询操作【重要
  10. MySQL入门(二) 数据库数据类型详解