Bluetooth ble in Android 5.0

Source: Internet
Author: User
Tags final integer requires uuid valid


I. Overview of bluetooth BLE (Bluetooth low energy) Introduction



Bluetooth Low Energy (BLE) technology is a low-cost, short-range, interoperable robust wireless technology that works in a licensed 2.4GHz-ism RF band. It was designed to be ultra low power (ULP) wireless technology from the outset.



The three characteristics of Bluetooth low energy technology have achieved ULP performance, these three features are maximum standby time, fast connection and low peak Send/Receive power.



Wireless "On" time is not very short will lead to a sharp reduction in battery life, so any necessary send or receive tasks need to be completed quickly. The first technique used by Bluetooth low-power technology to minimize wireless opening time is to search for other devices with only 3 "ad" channels, or to declare itself to be a device that seeks to establish a connection. By contrast, standard Bluetooth technology uses 32 channels.



Bluetooth Low energy technology "complete" one connection (that is, scan other devices, establish links, send data, authentication and properly end) is only 3ms. Standard Bluetooth technology requires hundreds of milliseconds to complete the same connection cycle. Again, the longer the wireless is switched on, the more battery energy is consumed.



Ii. Key Concepts:



(1) Generic Attribute profile (GATT)



Profile general specification for reading and writing attribute-class data through BLE connections. All the BLE application profiles are now based on GATT.



(2) Attribute Protocol (ATT)



The GATT is based on ATT protocol. Att for ble equipment to do a special optimization, specifically in the transmission process to use as little data. Each property has a unique UUID, and the properties are transmitted in the form of characteristics and services.



(3) characteristic



Characteristic can be understood as a data type, which includes a value and a description of 0 to multiple pairs of times value (descriptor).



(4) Descriptor



Description of the characteristic, such as scope, unit of measure, etc.



(5) Service



A collection of characteristic. For example, a service called "Heart Rate Monitor", which may contain multiple characteristics, may contain a Rate called "Heart measurement characteristic".



Third, related authority

<!-- Allows the program to discover and pair new Bluetooth devices -->

<uses-permission android:name="android.permission.BLUETOOTH" />
<!-- Allows the program to discover and pair new Bluetooth devices -->
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
The following two permissions are required by ScanBle (you can choose one)
Note: Standard Bluetooth and low power consumption are required to be scanned in Android 6.0 and above, and Android 6.0 can scan without the permission standard Bluetooth.
<!-- Access to CellID or WiFi, as long as the current device can receive the service signal of the base station, you can get the location information -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- More precise GPS requires this permission -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
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"/>
The code determines whether BLE is supported.
getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)
————————————————
Copyright statement: This article is the original article of CSDN blogger "Fuzhou - Sima Yi", following the CC 4.0 BY-SA copyright agreement, please reprint the original source link and this statement.
Original link: https://blog.csdn.net/chy555chy/article/details/51843429

Fourth, the main code introduction

Public class BluetoothBleDemo extends Activity {
    Private static final int REQUEST_CODE_BLUETOOTH_ENABLE = 1;
    Private static final int SCAN_PERIOD = 10000;
 
    Private BluetoothAdapter bluetoothAdapter;
    //import android.bluetooth.le.ScanCallback;
//Call requires API level 21 (current min is 18): new android.bluetooth.le.ScanCallback
//java.lang.SecurityException: Need ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission to get scan results
    Private ScanCallback scanCallback = new ScanCallback() {
        @Override
        Public void onBatchScanResults(List<ScanResult> results) {
            //Batch a batch
For(ScanResult result : results) {
System.out.println("onBatchScanResults " + result);
}
        }
 
        @Override
        Public void onScanResult(int callbackType, ScanResult result) {
System.out.println("onScanResult " + result);
 
BluetoothDevice device = result.getDevice();
System.out.println("Device name: " + device.getName());
//Returns the hardware address of this BluetoothDevice. For example, "00:11:22:AA:BB:CC".
System.out.println("Device address: " + device.getAddress());
System.out.println("Device service UUIDs: " + device.getUuids());
//Get the Bluetooth device type of the remote device.
System.out.println("Device type: " + device.getType());
//Possible values for the bond state are: BOND_NONE, BOND_BONDING, BOND_BONDED.
System.out.println("Device bondState: " + device.getBondState());

ScanRecord record = result.getScanRecord();
//Returns the advertising flags indicating the discoverable mode and capability of the device. Returns -1 if the flag field is not set.
System.out.println("Record advertise flags: 0x" + Integer.toHexString(record.getAdvertiseFlags()));
/*
txPowerLevel transmit power level
Returns the transmission power level of the packet in dBm. Returns Integer.MIN_VALUE if the field is not set. This value can be used to calculate the path loss of a received packet using the following equation:
Pathloss = txPowerLevel - rssi
*/
System.out.println("Record Tx power level: " + record.getTxPowerLevel());
System.out.println("Record device name: " + record.getDeviceName());
System.out.println("Record service UUIDs: " + record.getServiceUuids());
//Returns a map of service UUID and its corresponding service data.
System.out.println("Record service data: " + record.getServiceData());
//Returns a sparse array of manufacturer identifier and its respective manufacturer specific
System.out.println("Record manufacturer specific data: " + record.getManufacturerSpecificData());
 
 
//RSSI signal strength, which can be used to measure distance. The valid range is in dBm. The valid range is [-127, 127].
System.out.println("result rssi: " + result.getRssi());
//Returns timestamp since boot when the scan record was observed.
System.out.println("result timestampNanos: " + result.getTimestampNanos());
            
Switch(callbackType) {
Case ScanSettings.CALLBACK_TYPE_ALL_MATCHES:
Break;
Case ScanSettings.CALLBACK_TYPE_FIRST_MATCH:
Break;
Case ScanSettings.CALLBACK_TYPE_MATCH_LOST:
Break;
}
        }
 
        @Override
        Public void onScanFailed(int errorCode) {
System.out.println("onScanFailed errorCode = " + errorCode);
        }
    };
    Private BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
        @Override
        Public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            super.onServicesDiscovered(gatt, status);
        }
 
        @Override
        Public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            super.onCharacteristicChanged(gatt, characteristic);
        }
 
        @Override
        Public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicRead(gatt, characteristic, status);
        }
 
        @Override
        Public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicWrite(gatt, characteristic, status);
        }
 
        @Override
        Public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            super.onConnectionStateChange(gatt, status, newState);
        }
 
        @Override
        Public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            super.onDescriptorRead(gatt, descriptor, status);
        }
 
        @Override
        Public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            super.onDescriptorWrite(gatt, descriptor, status);
        }
 
        @OvErride
        Public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
            super.onMtuChanged(gatt, mtu, status);
        }
 
        @Override
        Public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
            super.onReadRemoteRssi(gatt, rssi, status);
        }
 
        @Override
        Public void onReliableWriteCompleted(BluetoothGatt gatt, int status) {
            super.onReliableWriteCompleted(gatt, status);
        }
    };
    Private Handler handler = new Handler() {
        @Override
        Public void handleMessage(Message msg) {
        }
    };
 
    @Override
    Protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        / / Determine whether the BLE feature is supported
        If(getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            initBluetoothBle();
        } else {
            showToast("this device can not support Bluetooth BLE");
        }
    }
 
    Private void initBluetoothBle() {
        //BluetoothAdapter is required for all Bluetooth operations in the Android system. It corresponds to the Bluetooth module of the local Android device. The BluetoothAdapter is a singleton in the whole system. Once you get the example of it, you can do the relevant Bluetooth operation.
        //BluetoothManager is supported on Android 4.3 or above (API level 18)
        BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();
    }
 
    /**
     * Turn on Bluetooth
     * Turn the Bluetooth module on and off, all can be monitored by ACTION_STATE_CHANGED broadcast
     */
    Private void requestEnable() {
        / / The first method to open Bluetooth, the system will prompt the application to open Bluetooth, whether authorized; disable will not have any prompts.
        //boolean result = bluetoothAdapter.enable();
        / / The second method to send a broadcast, a dialog box will pop up, choose whether to open Bluetooth, select Bluetooth is to open.
        If(bluetoothAdapter != null && !bluetoothAdapter.isEnabled()) {
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(intent, REQUEST_CODE_BLUETOOTH_ENABLE);
        }
    }
 
    /**
     * Scan BLE devices. Note that this method cannot scan standard Bluetooth, only BLE devices can be scanned.
     */
    Private void scanBleDevice(final boolean enabled) {
        If(bluetoothAdapter == null) {
            Return;
        }
        /*
        Why can't I use the singleton BluetoothAdapter again? The reasons are as follows:
        bluetoothAdapter.startLeScan() //deprecated
        Http://stackoverflow.com/questions/30223071/startlescan-replacement-to-current-api
        Remember that the method: public BluetoothLeScanner getBluetoothLeScanner () isn't static.
        If you do: BluetoothAdapter.getBluetoothLeScanner()
        You will get an error, since getDefaultAdapter() is a static method, but getBluetoothLeScanner() isn't.
        You need an instance of a BluetoothAdapter.
         */
        Final BluetoothLeScanner scanner = bluetoothAdapter.getBluetoothLeScanner();
        If(enabled) {
            //scan is divided into 2 categories, and before android L, the search condition is only uuid
            / / (1) directly search all peripheral peripheral (peripheral) devices, search results will be returned through this callback
            scanner.startScan(scanCallback);
            //(2) Search for devices based on filter criteria
            Final List<ScanFilter> scanFilters = new ArrayList<ScanFilter>();
            //uuid format 8-4-4-4-12 (32 bit, 128 bit)
            //address format (12 bits, 48 bits)
            scanFilters.add(new ScanFilter.Builder().setServiceUuid(ParcelUuid.fromString("00000000-0000-0000-0000-000000000000")).setDeviceAddress("00:00:00:00:00:00").build( ));
            ScanSettings scanSettings = new ScanSettings.Builder()
                    //require API 23
                    //.setCallbackType(0).setMatchMode(0).setNumOfMatches(0)
                    .setReportDelay(0).setScanMode(BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE).build();
            scanner.startScan(scanFilters, scanSettings, scanCallback);
            handler.postDelayed(new Runnable() {
                @Override
                Public void run() {
                    scanner.stopScan(scanCallback);
                }
            }, SCAN_PERIOD);
        } else {
            scanner.stopScan(scanCallback);
        }
    }
 
    /**
     * Two devices need to establish a GATT connection through BLE communication. Here we are talking about the Android device as the client, connected to the GATT Server. The data sending direction is always pushed from the server to the client.
     */
    Private void connectToGATTServer(BluetoothDevice device) {
        // The function succeeds, returning the BluetoothGatt object, which is the package of the GATT profile. Through this object, we can perform related operations on the GATT Client side. BluetoothGattCallback is used to pass some connection status and results.
        BluetoothGatt bluetoothGatt = device.connectGatt(this, false, gattCallback);
 
        / / Connect to a remote device
        Boolean connectResult = bluetoothGatt.connect();
        / / Search for connected services supported by the device
        Boolean discoverResult = bluetoothGatt.discoverServices();
        / / Disconnect the GATT from the remote device
        bluetoothGatt.disconnect();
        / / Close the GATT Client side
        bluetoothGatt.close();
        / / Read the specified character.
        //boolean readResult = bluetoothGatt.readCharacteristic(characteristic);
        / / Set to notify when the specified character value changes
        //boolean setResult = bluetoothGatt.setCharacteristicNotification(characteristic, enabled);
        / / Get the services supported by the remote device
        List<BluetoothGattService> gattServices = bluetoothGatt.getServices();
    }
 
    Private void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
     }
}
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.