Android Ble
16lz
2021-01-23
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更多明细.
更多相关文章
- 用Javascript判断访问来源操作系统, 设备, 浏览器类型
- android获取设备存储信息
- 第二部分:开发简要指南-第五章 支持不同的Android设备
- Android设备与USB设备的连接通讯
- Android设备到底侵犯了微软的什么专利
- Android设备的唯一ID
- Android TV蓝牙模块