爲了在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<ScanFilter> 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());
}
};