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. 编译V8静态库 for Android
  2. android HttpURLConnection 连接网络 读取返回数据
  3. Android通过http协议POST传输方式
  4. Android网络连接判断与处理
  5. Android设备与USB设备的连接通讯
  6. Android中textView自动识别电话号码,电子邮件,网址(自动加连接)
  7. Android主流三方库源码分析(一、深入理解OKHttp源码)
  8. Android多媒体分析(一)MediaScanner
  9. android 常用小知识点 tips(一)

随机推荐

  1. android Drawable资源
  2. Android(安卓)日记之二 pendingIntent简
  3. Android项目创建和项目目录图解
  4. Android(安卓)Canvas drawText实现中文垂
  5. 如何判断 两个不同包名的 Android(安卓)
  6. 现在有三个按钮,在FrameLayout下如何让这
  7. 将Eclipse工程迁移到Android(安卓)Stutio
  8. Android将Widget添加到自己的应用程序
  9. Android(安卓)约束布局ConstraintLayout
  10. android之电话号码查询