First, Key concepts:
Generic Attribute profile (GATT)Through BLE connection, read and write the profile General specification of the attribute class small data. All BLE application profiles are now based on GATT.
Attribute Protocol (ATT)GATT is based on the ATT protocol. The ATT has been specifically optimized for BLE devices by using as little data as possible during the transfer process. Each property has a unique UUID, and the properties are transferred as characteristics and services.
characteristicCharacteristic can be understood as a data type that includes a value and a description of 0 to multiple pairs of secondary value (descriptor).
DescriptorA description of the characteristic, such as the range, unit of measurement, etc.
ServiceA collection of characteristic. For example, a service called "heart rate Monitor" may contain multiple characteristics, which may contain a characteristic called "heart rate Measurement". Ii. roles and Responsibilities: Android devices interact with BLE devices with two sets of roles: central device and peripheral device (centrally vs. peripheral), GATT Server vs. GATT client. Central vs. Peripheral: The concept of center devices and peripherals is for the BLE connection itself. The central role is responsible for scan advertisement. And the peripheral role is responsible for make advertisement. GATT Server vs. GATT Client: These roles depend on how the two devices communicate with each other after the BLE connection succeeds. An example of this is an activity-tracking ble device and an Android device that supports BLE. The Android device supports the central role while the BLE device supports the peripheral role. Creating a BLE connection requires both of these roles to be present, only the central role is supported or only the peripheral role is supported, and the connection cannot be established. When a connection is established, it is necessary to transfer GATT data between them. Who does the server, who does the client, depends on the specific data transfer situation. For example, if an activity-traced BLE device needs to transmit sensor data to an Android device, the activity tracker naturally becomes the server side, and if the activity tracker needs to get updated information from an Android device, the Android device might be more appropriate as the server side. Third, the authority and feature: like the classic Bluetooth, the app uses Bluetooth, need to declare Bluetooth permissions, if you need to scan the device or operate Bluetooth settings, you also need Bluetooth_admin permissions: <uses-permission android: Name= "Android.permission.BLUETOOTH"/>
<uses-permission android:name= "Android.permission.BLUETOOTH_ADMIN"/> In addition to Bluetooth permissions, if required ble Feature also needs to declare uses-feature:<uses-feature android:name= "Android.hardware.bluetooth_le" android:required= "true"/ > When required is true, the app can only be installed on an Android device that supports BLE, and when required is false, Android devices are installed and run, and you need to determine if your device supports BLE feature when your code is running:/ /Use this check to determine whether BLE are 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 ();
Four, start Bluetooth: Before using Bluetooth ble, you need to confirm whether the Android device supports BLE feature (required is false), and also need to confirm that Bluetooth is turned on. If you find that BLE is not supported, you cannot use BLE-related features. If BLE is supported, but Bluetooth is not turned on, you need to turn on Bluetooth. To turn on Bluetooth: 1, get Bluetoothadapter Bluetoothadapter is required for all Bluetooth operations in Android, it corresponds to the Bluetooth module of the local Android device, Bluetoothadapter is a singleton in the whole system. When you get an example of it, you can do the relevant Bluetooth operation. Get the Bluetoothadapter code example as follows://initializes Bluetooth adapter.
Final Bluetoothmanager Bluetoothmanager =
(Bluetoothmanager) Getsystemservice (Context.bluetooth_service);
Mbluetoothadapter = Bluetoothmanager.getadapter (); Note: Get Bluetoothmanager through Getsystemservice and get bluetoothadapter through Bluetoothmanager. Bluetoothmanager above Android4.3 support (API level 18). 2, determine whether to support Bluetooth, and turn on Bluetooth to get to Bluetoothadapter, you also need to determine whether Bluetooth support, and Bluetooth is turned on. If not open, need to let the user open Bluetooth: 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);
Search for BLE devices: Search for BLE devices by calling Bluetoothadapter's Startlescan (). This method is called to pass in the
BluetoothAdapter.LeScanCallback
Parameters. So you need to implement
BluetoothAdapter.LeScanCallback
interface, the search results for BLE devices will be returned through this callback. Because the search needs to minimize power consumption, so in the actual use of the need to note: 1, when the corresponding device, immediately stop scanning, 2, do not cycle search device, set the appropriate time limit for each search. Avoid constant scanning and power consumption when the device is not in the available range. The sample code for the search is as follows:/**
* 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 ten 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);
}
...
}
...
If you only need to search the peripherals for the specified UUID, you can call
startLeScan(UUID[], BluetoothAdapter.LeScanCallback)
Method. Where the UUID array specifies the UUID of the GATT services supported by your application. Examples of implementations of Bluetoothadapter.lescancallback are as follows: 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 ();
}
});
}
}; Note: When searching, you can only search for traditional Bluetooth devices or BLE devices, which are completely independent and not searchable at the same time. Six, connecting GATT Server: Two devices through BLE communication, the first need to establish a GATT connection. Here we are talking about the Android device as the client side, connected to the GATT Server. To connect to the GATT Server, you need to call Bluetoothdevice's Connectgatt () method. This function takes three parameters: Context, AutoConnect (Boolean), and Bluetoothgattcallback object. Call Example: mbluetoothgatt = Device.connectgatt (this, false, Mgattcallback) The; function succeeds, returns the Bluetoothgatt object, which is the GATT Profile's encapsulation. With this object, we can perform the relevant operations on the client side of the GATT. Bluetoothgattcallback is used to pass some connection states and results. bluetoothgatt Typical examples of operations used: connect (): Connecting to a remote device. Discoverservices (): Search for the service supported by the connected device. Disconnect (): Disconnects the GATT connection to the remote device. Close (): Close the GATT client side. Readcharacteristic (characteristic): reads the specified characteristic. Setcharacteristicnotification (characteristic, enabled): Sets a notification when the specified characteristic value changes. GetServices () : Gets the services supported by the remote device. and so on. NOTE: 1. There is a succession relationship between some function calls. For example, you need connect to discoverservices first. 2, some function calls are asynchronous, the required value will not be returned immediately, but will be returned in the Bluetoothgattcallback callback function. For example Discoverservices and onservicesdiscovered callbacks, Readcharacteristic and Oncharacteristicread callbacks, SetcharacterisTicnotification and Oncharacteristicchanged callback and so on. http://www.blogjava.net/zh-weir/archive/2014/04/02/407373.html
Android4.3 bluetooth ble initial