Android低功耗蓝牙开发

android 专栏收录该内容
6 篇文章 0 订阅

初始化工作

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" })
			@Override
			public 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")
			@Override
			public void run() {
				// TODO Auto-generated method stub
				BluetoothAdapter 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() {

		@Override
		public 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>() {

							@Override
							public 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() {

					@Override
					public void run() throws Exception {
						connectionDisposable.dispose();
						connectionDisposable = null;
					}
				})

				.subscribe(new Consumer<RxBleConnection>() {

					@Override
					public void accept(RxBleConnection connection)
							throws Exception {

						onConnectionReceived(connection);
					}
				}, new Consumer<Throwable>() {

					@Override
					public 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 ConstantConditions
		Log.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[]>>() {

								@Override
								public ObservableSource<byte[]> apply(
										@NonNull ObservableSource<byte[]> arg0)
										throws Exception {
									return arg0;
								}
							}).observeOn(Schedulers.io())
					.subscribe(new Consumer<byte[]>() {

						@Override
						public void accept(byte[] arg0) throws Exception {
							//onNotificationReceived(arg0);

						}
					}, new Consumer<Throwable>() {

						@Override
						public void accept(Throwable arg0) throws Exception {
							// onNotificationSetupFailure();

							Log.i(TAG,
									"received-Exception:" + arg0.getMessage());
							
						}
					});
			rxBleConnection
					.setupNotification(/*UUID*/)
					.flatMap(
							new Function<ObservableSource<byte[]>, ObservableSource<byte[]>>() {

								@Override
								public ObservableSource<byte[]> apply(
										@NonNull ObservableSource<byte[]> arg0)
										throws Exception {
									return arg0;
								}
							}).observeOn(AndroidSchedulers.mainThread())

					.subscribe(new Consumer<byte[]>() {

						@Override
						public void accept(byte[] arg0) throws Exception {
							//onNotificationReceivedControl(arg0);
							//收到蓝牙设备发送信息
						}
					}, new Consumer<Throwable>() {

						@Override
						public 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[]>() {

						@Override
						public void accept(byte[] arg0) throws Exception {
							// TODO Auto-generated method stub
							//String str = HexString.bytesToHex(arg0);
							//Log.d(TAG, "onWriteFtcSuccess:" + str);
							
						}
					}, new Consumer<Throwable>() {

						@Override
						public void accept(Throwable arg0) throws Exception {
							// TODO Auto-generated method stub
							Log.d(TAG, "onWriteFailure:" + arg0.getMessage());
							
						}
					});
		}
	}

链接

RxAndroidBle工具包.
RxAndroidBle更多明细.

  • 1
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2020 CSDN 皮肤主题: 游动-白 设计师:白松林 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值