1.检测手机是否支持蓝牙4.0(一般手机4.3以上的android系统都支持)
[java] view plaincopy
- <span style="font-size:14px;"> if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
- showMsg(R.string.ble_not_supported);
- finish();
- }</span>
2.检测蓝牙是否打开,提示用户打开蓝牙(在此之前需要加相应的权限)
添加权限:
[html] view plaincopy
- <span style="font-size:14px;"> <uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
- <uses-permission android:name="android.permission.BLUETOOTH"/>
- <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/></span>
获取蓝牙适配器
[java] view plaincopy
- <span style="font-size:14px;">final BluetoothManager bluetoothManager =
- (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
- bluetoothAdapter = bluetoothManager.getAdapter();
- 如果蓝牙处于关闭状态,则通过下面代码提示用户启动蓝牙:
- Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
- startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
- </span>
3.启动关闭蓝牙,获取蓝牙状态
判断蓝牙状态:bluetoothAdapter.isEnabled()
开启蓝牙:bluetoothAdapter.enable();
关闭蓝牙:bluetoothAdapter.disable();
4.蓝牙启动后,就该搜索设备了
开启搜索: bluetoothAdapter.startLeScan(mLeScanCallback);
停止搜索: bluetoothAdapter.stopLeScan(mLeScanCallback);
搜索回调:
[java] view plaincopy
- private BluetoothAdapter.LeScanCallback mLeScanCallback =
- new BluetoothAdapter.LeScanCallback() {
- @Override
- public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- //在这里将搜到的设备显示到界面
- }
- });
- }
5.建立连接
[java] view plaincopy
- public boolean connect(BluetoothDevice device ) {
- if (device == null) {
- Log.w(TAG, "Device not found. Unable to connect.");
- return false;
- }
- mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
- return true;
连接时需要注册一个回调接口:
[html] view plaincopy
- private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
- //检测连接状态变化
- @Override
- public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
- if (newState == BluetoothProfile.STATE_CONNECTED) {
- } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
- }
- }
- @Override
- public void onServicesDiscovered(BluetoothGatt gatt, int status) {
- }
- @Override
- public void onCharacteristicRead(BluetoothGatt gatt,
- BluetoothGattCharacteristic characteristic,
- int status) {
- }
- //接收蓝牙回传数据
- @Override
- public void onCharacteristicChanged(BluetoothGatt gatt,
- BluetoothGattCharacteristic characteristic) {
- System.out.println("接收数据");
- byte[] data=characteristic.getValue();
- }
- //检测用户向蓝牙写数据的状态
- @Override
- public void onCharacteristicWrite(BluetoothGatt gatt,
- BluetoothGattCharacteristic characteristic, int status) {
- Log.e(TAG, "write status"+":"+status);
- if(status==BluetoothGatt.GATT_SUCCESS){
- System.out.println("——–write success—– status:");
- }
- super.onCharacteristicWrite(gatt, characteristic, status);
- }
- };
断开连接:
mBluetoothGatt.disconnect();
6.发送数据
//设置特性数据回传通知
[java] view plaincopy
- public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
- boolean enabled) {
- if (mBluetoothAdapter == null || mBluetoothGatt == null) {
- Log.w(TAG, "BluetoothAdapter not initialized");
- return;
- }
- if (mBluetoothGatt.setCharacteristicNotification(characteristic, enabled)) {
- BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
- UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
- descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
- mBluetoothGatt.writeDescriptor(descriptor);
- }
- }
- /**
- * 向设备发送数据
- * @param serviceUuid
- * @param characterUuid
- * @param notifactionUuid
- * @param data
- */
- public void writeDataToDevice(byte[] data){
- if (mBluetoothGatt == null) {
- return;
- }
- BluetoothGattService bluetoothGattService = mBluetoothGatt
- .getService(UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb"));//蓝牙设备中需要使用的服务的UUID
- if (bluetoothGattService == null) {
- Log.e(TAG, "service:"+mBluetoothGatt.getServices().size());
- Log.e(TAG, "service not found!");
- return;
- }
- BluetoothGattCharacteristic mCharac = bluetoothGattService
- .getCharacteristic("0000fff6-0000-1000-8000-00805f9b34fb");//需要使用该服务下具体某个特性的UUID
- if (mCharac == null) {
- Log.e(TAG, "HEART RATE Copntrol Point charateristic not found!");
- return;
- }
- BluetoothGattCharacteristic nCharacteristic=bluetoothGattService.getCharacteristic("0000fff7-0000-1000-8000-00805f9b34fb");//蓝牙模块向手机端回传特性UUID
- setCharacteristicNotification(nCharacteristic, true);
- Log.e(TAG, "data:"+Arrays.toString(data));
- mCharac.setValue(data); //设置需要发送的数据
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- writeCharacteristic(mCharac);
- }
- public void writeCharacteristic(BluetoothGattCharacteristic characteristic) {
- if (mBluetoothAdapter == null || mBluetoothGatt == null) {
- Log.e(TAG, "BluetoothAdapter not initialized");
- return;
- }
- boolean result=mBluetoothGatt.writeCharacteristic(characteristic);//开始写入数据
- if(result){
- Log.e(TAG, "write success!");
- }else {
- Log.e(TAG, "write fail!");
- }
- }