Android4.3 bluetooth ble Preliminary

Source: Internet
Author: User

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 in two sets of roles: Center and peripheral devices (central vs. peripheral);GATT Server vs. GATT client. Central vs. peripheral:The concept of central 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:Both roles depend on how the two devices communicate with each other after the BLE connection succeeds.  To illustrate:There is an active 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.   iii. Authority and feature:like classic Bluetooth, apps use Bluetooth, you need to declare Bluetooth permissions, and if you need to scan your device or operate Bluetooth settings, you'll 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 you need ble feature you also need to declare uses-feature:<uses-feature android:name= "Android.hardware.bluetooth_le" android:required= "true"/> On time 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 that your Android device supports BLE feature (required is false), and you 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 the Android system, 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 if Bluetooth is supported and turn on Bluetooth after you get to Bluetoothadapter, you also need to determine whether Bluetooth is supported, and whether Bluetooth is turned on. if not, you need to have the user turn on 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);
}  Five, search ble device:Search the BLE device by calling Bluetoothadapter's Startlescan (). You need to pass in parameters when calling this method BluetoothAdapter.LeScanCallback . so you need to implement the BluetoothAdapter.LeScanCallback interface, the BLE device search results will be returned through this callback.  because the search needs to minimize power consumption, you need to be aware of the actual use: 1. When the corresponding equipment is found, stop scanning immediately;2, do not cycle search devices, 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 peripheral for the specified UUID, you can call the 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.   Vi. Connection to the 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. Invocation Example: Mbluetoothgatt = Device.connectgatt (this, false, mgattcallback); The function succeeds and returns the Bluetoothgatt object, which is the encapsulation of the GATT profile. 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 Several examples of operations that are used in general: Connect (): Connects to the 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.

Android4.3 bluetooth ble Preliminary

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.