Android Bluetooth Low Energy官方文档翻译

Android Bluetooth Low Energy官方文档翻译

    Android4.3(API18)为Bluetooth Low Energy(简称BLE)的核心功能提供了平台支撑,App能够通过它用来发现设备,查询服务,以及读写特性。与传统的蓝牙相比,BLE设计的最大特征就是低功耗。这使得Android的APP能够与具备低功耗的BLE设备进行通信,比如距离传感器,心跳检测,健身设备等等。

关键术语和概念

下面是一些关于BLE的核心术语和概念
  • Generic Attribute Profile(GATT) gatt是一个通用的规范,在BLE链路上收发称为“attribute”的数据块。目前所有的低功耗的应用都是基于GATT的。蓝牙SIG 为低功耗设备定义了很多的规范。规范是说明一个设备如何在一个特定的场合工作。需要注意的是,一个设备能够应用多个规范。比如说一个设备就包含了心跳检测仪和电池电量检测。
  • Attribute Protocol(ATT) GATT是建立在ATT的协议之上,他们也称之为GATT/ATT。ATT在对运行了BLE的设备进行了优化。所以,它运用尽可能少的字节。每个属性通过UUID唯一的来标识,每一个UUID使用128位bit来表示。属性通过ATT被格式化为characteristics和services。
  • Characteristic 一个Characteristic包含一个变量和一个0-n的descriptors来形容Characteristic的值。一个Characteristic可以看作是一个类型,简单的可以理解为类。
  • Descriptor Descriptor定义属性并且用来描述一个Characteristic的值。比如:一个descriptor可以规定一个可读的描述,或者一个characteristic变量可接受的范围,或者一个characteristic变量特定的测量单位。
  • Service 一个Service是一个Characteristic是的集合。比如你有一个称之为“心跳测试仪”的Service,包括很多的Characteristics比如“heart rate measurement”.

角色与责任

以下是Android设备与BLE设备交互时的角色与责任:
  • 中央vs外围设备 这是应用于BLE连接本身。中央设备进行扫描,搜寻广播,外围设备发送广播。
  • GATT服务的VSGATT客户端 两个设备通过广播进行相互的交流直到他们创建连接。

    为了两者之间的区别,想象你又一个Android手机和一个拥有BLE设备的活动追踪器。手机处在于一个中央的角色,活动追踪器处于一个外围设备的角色(为了建立连接,你需要知道只支持外围设备的两方或者支持中央设备的两方不能够进行通信)。
    
    一旦手机和活动追踪器建立起连接,他们就开始一方向另一方传输GATT数据包。谁作为服务器取决于他们传输的数据类型。比如说,活动追踪器想要将传感器数据传输到手机上,活动追踪器就作为一个服务器。如果活动追踪器想要接收来自于手机端的更新,显示是手机作为服务器,
    
    在文档例子中,APP(运行在Android设备上)就是一个GATT客户端。这个app从GATT服务器获取数据,GATT服务器就是一个支持心跳配置的心跳检测仪。但是你可以自己设计android app去扮演GATT服务端角色。更多信息见BluetoothGattServer。
    

BLE的权限

    为了在你的应用上使用蓝牙特性,你必须声明BLUETOOTH的权限。利用这个权限去执行蓝牙通信,比如请求连接,接收连接,传输数据。

    如果想让你的app初始化设备或者操纵蓝牙设置,你必须得声明BLUETOOTH_ADMIN权限。注意:如果你利用BLUETOOTH_ADMIN权限,你必须同时拥有BLUETOOTH权限。

    在你的应用的manifest文件当中声明蓝牙权限。比如:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

    如果你想在你的app当中声明只支持ble的设备,在manifest当中还应当包括:
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>


    但是,如果你想使得你的设备不支持ble,你只需要在上面的设置中,设置require="fasle".在运行的时候你就可以用PackageManager.hasSystemFeature()判断是否支持BLE设备。
// Use this check to determine whether BLE is supported on the device. Then
// you can selectively disable BLE-related features.
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
    Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
    finish();
}

设置BLE

    在你的应用与BLE通信之前,你需要确认BLE是否支持该设备,如果支持确认已经启动。注意只有当你在<uses-feature.../>设置为false的时候才是有必要的。

    如果BLE不被支持,你应该禁止使用BLE特性。如果BLE是支持的但是没有开启,你可以无需离开应用就启动蓝牙。使用BluetoothAdapter通过两部完成该设置。
(1)得到BluetoothAdapter
     所有的蓝牙活动都需要BlueAdapter。BluetoothAdapter代表设备本身的蓝牙适配器(蓝牙无线)。在整个系统当中有且只有一个蓝牙适配器,应用能够利用它进行交互。下面的代码片段表面怎样获得适配器。注意该方法使用getSystemService() 返回一个BluetoothManager,能够通过它得到BluetoothAdapter。Android 4.3(API 18)引入BluetoothManager。
// Initializes Bluetooth adapter.
final BluetoothManager bluetoothManager =
        (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
(2)使用蓝牙
    接下来,你需要保证蓝牙是可以使用的,通过isEnable()可以查看蓝牙是否可以使用。如果返回false表示不能。下面的代码片段检查蓝牙是否可以使用,如不能,显示提示用户去开启蓝牙。
private BluetoothAdapter mBluetoothAdapter;
...
// Ensures Bluetooth is available on the device and it is enabled. If not,
// displays a dialog requesting user permission to enable Bluetooth.
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}

查找BLE设备

    查找BLE设备,你能够利用startLeScan()方法。这个方法需要用BluetoothAdapter.LeScanCallback作为一个参数。你必须实现这个callback接口,能够返回扫描结果。扫描十分消耗电量,你需要准信如下准则:
  • 一旦你扫描到你想要的设备,马上停止扫描
  • 别循环扫描,给扫描一个时间限制。以前可用的设备现在可能已经超出了范围,继续扫描只可能消耗电量。
  • 下面的代码片段显示开始或者停止扫描:
/**
 * Activity for scanning and displaying available BLE devices.
 */
public class DeviceScanActivity extends ListActivity {

    private BluetoothAdapter mBluetoothAdapter;
    private boolean mScanning;
    private Handler mHandler;

    // Stops scanning after 10 seconds.
    private static final long SCAN_PERIOD = 10000;
    ...
    private void scanLeDevice(final boolean enable) {
        if (enable) {
            // Stops scanning after a pre-defined scan period.
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mScanning = false;
                    mBluetoothAdapter.stopLeScan(mLeScanCallback);
                }
            }, SCAN_PERIOD);

            mScanning = true;
            mBluetoothAdapter.startLeScan(mLeScanCallback);
        } else {
            mScanning = false;
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
        }
        ...
    }
...
}
    如果你只想扫描特定型号的外围设备,你能够利用 startLeScan(UUID[], BluetoothAdapter.LeScanCallback),需要提供你一个UUID的数组并且应用支持。
    下面是一个BluetoothAdapter.LeScanCallback的运用,实现这个接口去得到扫描结果:
private LeDeviceListAdapter mLeDeviceListAdapter;
...
// Device scan callback.
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() {
               mLeDeviceListAdapter.addDevice(device);
               mLeDeviceListAdapter.notifyDataSetChanged();
           }
       });
   }
};
注意:只能够扫描BLE设备或者传统的蓝牙设备,不能同时扫描。

连接到GATT服务端

    与BLE交互的第一步就是去连接,或者说,连接到GATT的服务端。为了连接到BLE设备的服务端,需要利用到 connectGatt() 方法,这个方法涉及到三个参数:Context上下文,autoConnect(boolean值,一旦可用是否自动连接),BluetoothGattCallback。
mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
    连接到GATT服务端时,由BLE设备充当主机,并返回一个 BluetoothGatt实例。然后你可以该实例进行GATT客户端操作。请求(手机的APP)作为GATT客户端。BluetoothGattCallback用作将结果传输到客户端,比如连接状态,以及进一步的GATT客户端操作。
    在例子当中,这个BLE app提供一个Activity(DeviceControlActivity)来连接,呈现数据,呈现这个设备所支持的 GATT services and characteristics,通过Android BLE API进行与BLE设备进行交互。
// A service that interacts with the BLE device via the Android BLE API.
public class BluetoothLeService extends Service {
    private final static String TAG = BluetoothLeService.class.getSimpleName();

    private BluetoothManager mBluetoothManager;
    private BluetoothAdapter mBluetoothAdapter;
    private String mBluetoothDeviceAddress;
    private BluetoothGatt mBluetoothGatt;
    private int mConnectionState = STATE_DISCONNECTED;

    private static final int STATE_DISCONNECTED = 0;
    private static final int STATE_CONNECTING = 1;
    private static final int STATE_CONNECTED = 2;

    public final static String ACTION_GATT_CONNECTED =
            "com.example.bluetooth.le.ACTION_GATT_CONNECTED";
    public final static String ACTION_GATT_DISCONNECTED =
            "com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";
    public final static String ACTION_GATT_SERVICES_DISCOVERED =
            "com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";
    public final static String ACTION_DATA_AVAILABLE =
            "com.example.bluetooth.le.ACTION_DATA_AVAILABLE";
    public final static String EXTRA_DATA =
            "com.example.bluetooth.le.EXTRA_DATA";

    public final static UUID UUID_HEART_RATE_MEASUREMENT =
            UUID.fromString(SampleGattAttributes.HEART_RATE_MEASUREMENT);

    // Various callback methods defined by the BLE API.
    private final BluetoothGattCallback mGattCallback =
            new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status,
                int newState) {
            String intentAction;
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                intentAction = ACTION_GATT_CONNECTED;
                mConnectionState = STATE_CONNECTED;
                broadcastUpdate(intentAction);
                Log.i(TAG, "Connected to GATT server.");
                Log.i(TAG, "Attempting to start service discovery:" +
                        mBluetoothGatt.discoverServices());

            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                intentAction = ACTION_GATT_DISCONNECTED;
                mConnectionState = STATE_DISCONNECTED;
                Log.i(TAG, "Disconnected from GATT server.");
                broadcastUpdate(intentAction);
            }
        }

        @Override
        // New services discovered
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
            } else {
                Log.w(TAG, "onServicesDiscovered received: " + status);
            }
        }

        @Override
        // Result of a characteristic read operation
        public void onCharacteristicRead(BluetoothGatt gatt,
                BluetoothGattCharacteristic characteristic,
                int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
            }
        }
     ...
    };
...
}
    当一个特定的回调被触发的时候,它会调用相应的broadcastUpdate()辅助方法并且传递给它一个action。注意在该部分中的数据解析按照蓝牙心率测量配置文件规格进行。
private void broadcastUpdate(final String action) {
    final Intent intent = new Intent(action);
    sendBroadcast(intent);
}

private void broadcastUpdate(final String action,
                             final BluetoothGattCharacteristic characteristic) {
    final Intent intent = new Intent(action);

    // This is special handling for the Heart Rate Measurement profile. Data
    // parsing is carried out as per profile specifications.
    if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
        int flag = characteristic.getProperties();
        int format = -1;
        if ((flag & 0x01) != 0) {
            format = BluetoothGattCharacteristic.FORMAT_UINT16;
            Log.d(TAG, "Heart rate format UINT16.");
        } else {
            format = BluetoothGattCharacteristic.FORMAT_UINT8;
            Log.d(TAG, "Heart rate format UINT8.");
        }
        final int heartRate = characteristic.getIntValue(format, 1);
        Log.d(TAG, String.format("Received heart rate: %d", heartRate));
        intent.putExtra(EXTRA_DATA, String.valueOf(heartRate));
    } else {
        // For all other profiles, writes the data formatted in HEX.
        final byte[] data = characteristic.getValue();
        if (data != null && data.length > 0) {
            final StringBuilder stringBuilder = new StringBuilder(data.length);
            for(byte byteChar : data)
                stringBuilder.append(String.format("%02X ", byteChar));
            intent.putExtra(EXTRA_DATA, new String(data) + "\n" +
                    stringBuilder.toString());
        }
    }
    sendBroadcast(intent);
}
    返回DeviceControlActivity,这些时间都是通过一个广播接受者来完成:
// Handles various events fired by the Service.
// ACTION_GATT_CONNECTED: connected to a GATT server.
// ACTION_GATT_DISCONNECTED: disconnected from a GATT server.
// ACTION_GATT_SERVICES_DISCOVERED: discovered GATT services.
// ACTION_DATA_AVAILABLE: received data from the device. This can be a
// result of read or notification operations.
private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();
        if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
            mConnected = true;
            updateConnectionState(R.string.connected);
            invalidateOptionsMenu();
        } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
            mConnected = false;
            updateConnectionState(R.string.disconnected);
            invalidateOptionsMenu();
            clearUI();
        } else if (BluetoothLeService.
                ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
            // Show all the supported services and characteristics on the
            // user interface.
            displayGattServices(mBluetoothLeService.getSupportedGattServices());
        } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
            displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
        }
    }
};

读取BLE属性

    一旦Android的app连接到GATT服务端,搜寻服务,它能够读取和写入属性,下面的代码通过服务端的services和Characteristic,将他们在UI上呈现:
public class DeviceControlActivity extends Activity {
    ...
    // Demonstrates how to iterate through the supported GATT
    // Services/Characteristics.
    // In this sample, we populate the data structure that is bound to the
    // ExpandableListView on the UI.
    private void displayGattServices(List<BluetoothGattService> gattServices) {
        if (gattServices == null) return;
        String uuid = null;
        String unknownServiceString = getResources().
                getString(R.string.unknown_service);
        String unknownCharaString = getResources().
                getString(R.string.unknown_characteristic);
        ArrayList<HashMap<String, String>> gattServiceData =
                new ArrayList<HashMap<String, String>>();
        ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData
                = new ArrayList<ArrayList<HashMap<String, String>>>();
        mGattCharacteristics =
                new ArrayList<ArrayList<BluetoothGattCharacteristic>>();

        // Loops through available GATT Services.
        for (BluetoothGattService gattService : gattServices) {
            HashMap<String, String> currentServiceData =
                    new HashMap<String, String>();
            uuid = gattService.getUuid().toString();
            currentServiceData.put(
                    LIST_NAME, SampleGattAttributes.
                            lookup(uuid, unknownServiceString));
            currentServiceData.put(LIST_UUID, uuid);
            gattServiceData.add(currentServiceData);

            ArrayList<HashMap<String, String>> gattCharacteristicGroupData =
                    new ArrayList<HashMap<String, String>>();
            List<BluetoothGattCharacteristic> gattCharacteristics =
                    gattService.getCharacteristics();
            ArrayList<BluetoothGattCharacteristic> charas =
                    new ArrayList<BluetoothGattCharacteristic>();
           // Loops through available Characteristics.
            for (BluetoothGattCharacteristic gattCharacteristic :
                    gattCharacteristics) {
                charas.add(gattCharacteristic);
                HashMap<String, String> currentCharaData =
                        new HashMap<String, String>();
                uuid = gattCharacteristic.getUuid().toString();
                currentCharaData.put(
                        LIST_NAME, SampleGattAttributes.lookup(uuid,
                                unknownCharaString));
                currentCharaData.put(LIST_UUID, uuid);
                gattCharacteristicGroupData.add(currentCharaData);
            }
            mGattCharacteristics.add(charas);
            gattCharacteristicData.add(gattCharacteristicGroupData);
         }
    ...
    }
...
}

接收GATT通知

    当设备上的特性改变之后回通知BLE APP,下面这段代码显示怎样为characteristic设置通知,利用setCharacteristicNotification()方法:
private BluetoothGatt mBluetoothGatt;
BluetoothGattCharacteristic characteristic;
boolean enabled;
...
mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
...
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
        UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
mBluetoothGatt.writeDescriptor(descriptor);
    一旦characteristic发送通知,onCharacteristicChanged() 回调就会触发,如果远程设备的characteristic改变。
@Override
// Characteristic notification
public void onCharacteristicChanged(BluetoothGatt gatt,
        BluetoothGattCharacteristic characteristic) {
    broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}

关闭客户端APP

    当运用app的客户端结束之后,应该通过close(),系统立即释放资源:
public void close() {
    if (mBluetoothGatt == null) {
        return;
    }
    mBluetoothGatt.close();
    mBluetoothGatt = null;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值