为了在app中使用蓝牙功能,必须声明蓝牙权限BLUETOOTH。利用这个权限去执行蓝牙通信,例如请求连接、接受连接、和传输数据。如果想让你的app启动设备发现或操纵蓝牙设置,必须声明BLUETOOTH_ADMIN权限。
在AndroidManifest.xml文件中添加权限:
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
如果想声明你的app只为具有BLE的设备提供,还需要声明uses-feature:
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
当required为true时,应用只能在支持BLE的Android设备上安装运行;required为false时,Android设备均可正常安装运行,需要在代码运行时判断设备是否支持BLE feature:
// 使用此检查确定BLE是否支持在设备上,然后你可以有选择性禁用BLE相关的功能
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
finish();
}
初始化:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 初始化蓝牙适配器
final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
judgeBluetoothEnable();
}
//判断蓝牙状态
private void judgeBluetoothEnable() {
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
enableBt = false;
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
} else {
enableBt = true;
mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
}
}
private static final ParcelUuid SAMPLE_UUID = new ParcelUuid(UUID.fromString("6e400000-b5a3-f393-e0a9-e50e24dcca9c"));
//private static final String DEVICE_NAME_STRING = "LeShoe01";
//搜索蓝牙设备
private void scanLeDevice(final boolean enable) {
if (enable) {
mScanning = true;
List bleScanFilters = new ArrayList<>();
//添加过滤规则
bleScanFilters.add(new ScanFilter.Builder().setServiceUuid(SAMPLE_UUID).build());
// bleScanFilters.add(new ScanFilter.Builder().setDeviceName(DEVICE_NAME_STRING).build());
ScanSettings bleScanSettings = new ScanSettings.Builder().build();
Log.d(TAG, "Starting scanning with settings:" + bleScanSettings + " and filters:" + bleScanFilters);
//开始搜索
mBluetoothLeScanner.startScan(bleScanFilters, bleScanSettings, mScanCallback);
} else {
mScanning = false;
stopScanning();
}
}
//停止搜索
private void stopScanning() {
if (mBluetoothLeScanner != null) {
Log.d(TAG, "Stop scanning.");
mBluetoothLeScanner.stopScan(mScanCallback);
}
}
//BLE设备搜索回调
private ScanCallback mScanCallback = new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
//结果返回
BluetoothDevice device = result.getDevice();
}
};
//连接设备
mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
if (newState == BluetoothProfile.STATE_CONNECTED) {// 当蓝牙设备已经连接
Log.i(TAG, "Connected to GATT server.");
gatt.discoverServices();
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {// 当设备无法连接
Log.e(TAG, "Disconnected from GATT server !");
}
}
//发现服务
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
Log.i(TAG, "onServicesDiscovered GATT_SUCCESS");
BluetoothGattService service = gatt.getService(UUID.fromString("6e400000-b5a3-f393-e0a9-e50e24dcca9c"));
Txcharacteristic = service.getCharacteristic(UUID.fromString("6e400002-b5a3-f393-e0a9-e50e24dcca9c"));
Rxcharacteristic = service.getCharacteristic(UUID.fromString("6e400003-b5a3-f393-e0a9-e50e24dcca9c"));
//接收通知
gatt.setCharacteristicNotification(Rxcharacteristic, true);
//发送数据
Txcharacteristic.setValue(new byte[]{0x3b});
gatt.writeCharacteristic(Txcharacteristic);
} else {
Log.e(TAG, "onServicesDiscovered status: " + status);
}
}
//收到通知
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
Log.i(TAG, "---------- onCharacteristicChanged ----------");
//获取数据
byte[] result = characteristic.getValue();
StringBuilder sb = new StringBuilder();
String hv = null;
for (byte b : result) {
hv = Integer.toHexString(b & 0xFF);
if (hv.length() < 2) {
sb.append(0);
}
sb.append(hv);
}
Log.i(TAG, "onCharacteristicChanged characteristic.getValue(): " + sb.toString());
}
};