android-BluetoothLeGatt | Migrated : - This repo has been migrated to github | Wifi library
kandi X-RAY | android-BluetoothLeGatt Summary
kandi X-RAY | android-BluetoothLeGatt Summary
This repo has been migrated to [github.com/android/connectivity][1]. Please check that repo for future updates. Thank you!.
Support
Quality
Security
License
Reuse
Top functions reviewed by kandi - BETA
- Connect to Bluetooth LE component
- Makes an appropriate filter for GATT updates
- Connects to a GATT device
- Called when a menu item is selected
- Stop Bluetooth device
- Displays a list of supported GATT services
- Look up the attributes for a given uuid
- Broadcast an update to an update
- Broadcast a Heart Rate measurement
- Handles a menu item select
- Disconnects and cancels the existing connection
- Returns a list of supported GATT services
- Requests a single Gatt characteristic
- Unbind from Bluetooth
- Clears the list
- Clears the UI
- Updates the connection state
- Finish the activity or disable Bluetooth
- Sets the menu menu
- Enables or disables a specific Bluetooth characteristic
- Ensures that the Bluetooth device is activated
- Initializes the BluetoothAdapter
- Called when a Bluetooth device is clicked
- Initializes the options menu
- Initializes the activity bar
- Initialize Services
android-BluetoothLeGatt Key Features
android-BluetoothLeGatt Examples and Code Snippets
Community Discussions
Trending Discussions on android-BluetoothLeGatt
QUESTION
I am developing an android app with BLE API from android. My app needs to connect to a BLE device, and remain connected as long as it is in range and turned on. I need to read data from it, and write data to it.
I am trying to follow the MVP architecture pattern, not strictly since activities are the starting point. But anyway, I wanted to know where should I put the interaction with Bluetooth? I am searching for answers for the following questions. I have searched StackOverflow, but couldn't find what I was looking for.
- Should it be in a service bounded to the UI just like in googlesample ble app ? But, I think that would break the whole mvp architecture.
- Should it be a bounded service at all ? If no, what would be the best way to implement the service? In my mind, if it's not bounded to the view, and there is a callback from the background service to display something on the UI, there is a possibility of undefined behavior.
- Who should initiate the Bluetooth interaction ? The application class or some activity ?
I am looking for mainly architectural guidance, and best way to go about developing this app.
...ANSWER
Answered 2018-Jan-06 at 22:20Since you have the requirement that the Bluetooth connection should keep working in the background, you should have a Foreground Service somewhere running in your app process. This will make sure your app process will be kept alive, but requires an icon to be displayed in the phone/tablet's top bar.
Whether you actually put your BLE code in this service class or not doesn't matter for the functionality.
There are of course many ways to achieve good architecture but here is my approach.
My approach would be to have a singleton class that handles all your BLE scanning, connections and GATT interactions (from now on called Manager). Since some BLE operations needs an Android Context, a good way is to use the Application context as context. Either follow Static way to get 'Context' on Android? to be able to fetch that context at any time or subclass the Application class and from its onCreate
call some initialization method in your Manager and pass the context. Now you can keep all BLE functionality completely separated from Android Service/Activity/Application stuff. I don't really see the point in using bounded services etc. as long as you keep everything in the same process.
To implement a scan functionality, you can have a method in your Manager that creates Scanner objects. Write the Scanner class as a wrapper to Android's BLE scanner and expose methods to start/stop scan. When you create a Scanner that method should also take an interface as argument used for callbacks (device reports and errors). This class can now be used in for example an Activity. Just make sure that the scanner gets stopped in the Activity's onStop
method to avoid leakage of objects.
There are several reasons for having a wrapped custom Scanner object instead of using Android's BLE scan API directly in the Activity. First you can apply the appropriate filtering and processing of advertising packets so it handles your type of peripheral and can show high level parameters (decoded from advertising data) in your custom advertising report callback. The manager should also listen to broadcasts when Bluetooth gets started/stopped/restarted and keep track of all started Scanners so the Scanners are restarted seamlessly when Bluetooth restarts (if you want this functionality). You may also want to keep track of timestamps of all scan starts/stops so you can workaround the new restrictions in Nougat that limits it to 5 scans per 30 seconds.
Use a similar approach when you want to connect to your peripherals. You can for example let the Manager create Device objects which have methods to start/stop the connection and have a callback interface to report events. For each supported feature (for example read some remote value) you should expose a method which starts the requests and have a callback which is called when the result arrives. Then your Manager and Device class takes care of the GATT stuff (including enqueuing all your GATT requests so you only have one outstanding GATT operation at a time). Just make sure you can always abort or ignore the result when you don't want the result, for example if an Activity's onStop
or onDestroy
method is called.
Since you probably want to reconnect automatically in case the device gets disconnected, you should use the autoConnect
flag and set it to true when establishing the connection, which assures this. Again, the Manager should keep track of all active Device objects and automatically recreate the BluetoothGatt object when Bluetooth is restarted.
To be able to display different kind of UI stuff, like for example automatically show a warning message in your Activity when Bluetooth is turned off and remove it when Bluetooth is turned on, you should be able to register Listeners to your Manager. Have a method in your Manager for registering/unregistering a listener (which is really just a Callback) object, keep track of all the listeners and when Bluetooth state change happens, call all listeners. Then in your Activity's onStart
you register a listener and in onStop
you unregister it. You can have a similar approach for your Device's BLE notifications, where applicable.
What's left is how you deal with different Threads. As you might know most BLE callbacks from Android's API happen on Binder threads, so you may not update the UI from them. If you otherwise in your app don't use anything other than the main thread, you can for example post all invocations of callbacks in the Manager to the main thread, or maybe move to the main thread directly when the callback from Android's BLE stack arrives (but then be aware of things like https://bugs.chromium.org/p/chromium/issues/detail?id=647673). Just make sure you never touch the same variables from different threads.
Also if you target API 23 or higher you need UI code to let the user give permission to Location to be able to start scan. I suggest you implement this in your UI code and not in the Manager, or implement some "wrapper" or helper method in the Manager to do this.
QUESTION
I am implementing a heart sensor to an existing application, I am using google BLE connectivity example as my base (https://github.com/googlesamples/android-BluetoothLeGatt). The thing is that in the example when they connect to a device, they show all of the characteristics and you need to press on one to actually see the data. I am trying to automize that part so in the end you should just press on heart monitor device and the right characteristic should automatically connect.
So I did some changes to the original code so now I am getting "Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object" error. full error:
...ANSWER
Answered 2019-Jan-23 at 15:11Did you tried call getContext().getSystemService()?
QUESTION
I modified the BLE app so that it plots data that's coming from a sensor, shown below:
Now, when I close the app I want to be able to save the plot, so that next time when I open the app again, I can continue plot the graph instead of starting over.
I googled around and found this person recommending using Icepick library to save the app state. I tried his method but it didn't work, maybe I am using it wrong.
I added the @state variables at the top, added the @overide function and added the restoreInstanceState() function in my onCreate. Then I tried to store the last x and y value into the @state variables that I declared at the top of my code. Following is my code structure in DeviceControlActivity.java.
...ANSWER
Answered 2018-Apr-29 at 06:39Ended up using SharedPreferences to save and get values:
global variable:
public SharedPreferences pref;
inside oncreate():
pref = getSharedPreferences("MyPrefs",Context.MODE_PRIVATE);
QUESTION
I am developing an android app that fetches temperature from a bluetooth thermometer. I followed the instructions on the google developer page.
https://developer.android.com/guide/topics/connectivity/bluetooth-le.html
I could scan the devices and get connected to the thermometer. I am exactly using the same code from the following github.
https://github.com/googlesamples/android-BluetoothLeGatt/
Instead of using the the heart rate service and associated characteristics. I am using temperature service and the characteristic. I have changed these value on the following page that I downloaded from github
android-BluetoothLeGatt/Application/src/main/java/com/example/android/bluetoothlegatt/SampleGattAttributes.java
I using the following bluetooth thermometer.
http://www.cooper-atkins.com/Products/Blue2/
This is the API document I got from COOPER-ATKINS.
https://drive.google.com/open?id=1eq93Qc6uy0Vv9KompukLuIUnJK4B-e-0
In page 6 I have highlighted the service uuids and characteristic uuids I have replaced in the github code.
I could read the temperature data but only once. If the temperature changes I could not see the temperature value is refreshed in app automatically. I have to hit the temperature list button to get the recent value. Could anyone suggest what I am missing or doing wrong.
Please let me know if you need more info.
...ANSWER
Answered 2018-Feb-28 at 03:20The characteristics you highlighted have both read and indicate property.
Reading the characteristic (Calling BluetoothGatt.readCharacteristic in Android) only obtains the value at that instant by definition.
You have to enable the indication to get every update of the value. You can find how to enable a notification (not indication) on this SO thread. You can substitute the constant value to enable indication.
QUESTION
I've created an android app of BLE GATT server, but I can't find where I write the name of the GATT Server, I mean the device name that appears in search.
I tried both https://github.com/androidthings/sample-bluetooth-le-gattserver https://github.com/googlesamples/android-BluetoothLeGatt
and can't find where the name of the device being written? how BLE search decide what name to show?
...ANSWER
Answered 2017-Sep-28 at 11:24I've just tried:
BluetoothAdapter.getDefaultAdapter().setName("MyGattServerName");
and it worked!!!
QUESTION
I wrote a simple application to be able to write to specific characteristic. I based my app on google example - https://github.com/googlesamples/android-BluetoothLeGatt . I added buttons that upon connection gives possibility to write to specific characteristic a byte.
Now what I noticed is that after connection for few seconds (always less than 5) it works fine, but then function writeCharacteristic (https://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#writeCharacteristic(android.bluetooth.BluetoothGattCharacteristic)) starts to return false. I debugged and it turns out that device is busy. I am able to successfully call writeCharacteristic every 1.5 second which compared to no delay in first few seconds of connection is very slow.
Here is my snippet with onClick function:
...ANSWER
Answered 2017-Sep-23 at 20:08That the device is "busy" does just mean that a response is pending. Android's API requires that you wait for the corresponding callback (like onCharacteristicWrite for writes) after you issue a new request. If you think it takes too much time you can lower the connection interval.
QUESTION
I would like to use the Bluetooth Low Energy (BLE) technology to make connection between two supported phones (currently I would like to use it with only Android phones, iOS support is possible in the future). The client which starts the connection should be an Android device with API level 19 (KitKat) or above.
I've read several tutorials and tried several examples about how to achieve a working Bluetooth LE scanning on Android (including Google's own sample project called BluetoothLeGatt). The following things are already done in my test project, based on Android documentations and many SO questions and answers:
- Minimum SDK version is set on API level 18 (that's where Android started to support Bluetooth LE)
- The mandatory Bluetooth permissions (
BLUETOOTH
andBLUETOOTH_ADMIN
) granted inAndroidManifest.xml
, plus theandroid.hardware.bluetooth_le
feature is set withtrue
value - The
ACCESS_FINE_LOCATION
andACCESS_COARSE_LOCATION
permissions are also needed on API level 23 and above - so they are in the manifest file too (withuses-permission
ANDuses-permission-sdk-23
tags), plus theandroid.hardware.location.gps
feature is set - The user also is asked to grant the permissions mentioned above at app's first start
- Bluetooth and Location (GPS) are turned on
- Scanning for devices starts after permissions are granted (managed with clicking a button)
- On API level 21 and above the newer API methods are used instead of the ones deprecated since the same API level
Despite all the things listed above, NO DEVICES FOUND AFTER STARTING THE SCAN. Currently I'm using a 6.0 (Marshmallow, API 23) device and everything seems fine - except finding the devices around me with Bluetooth turned on and set to always visible. But of course, from the device settings I can find all of them, so I don't understand what could be the missing / wrong thing (by the way, it's the first time I'm dealing with something related to Bluetooth... :) ). It looks like the scanning process starts seamlessly, but none of the callback methods are responding any single message or variable.
And YES, I KNOW: there are a lot of questions on SO about this with people saying "everything works after making the changes above"... and unfortunately it does not work for me, so I'm a bit frustrated about this problem. If anyone reading this topic faced before with anything similar to this, and writes a comment or answer down there, I will really appreciate it! :)
TO MAKE THE QUESTION SECTION EVEN LONGER:
My activity:
...ANSWER
Answered 2017-May-24 at 12:08The solution for my problem was to understand more deeply how BLE works. What I needed to realize is that BLE capable devices are not showing themselves automatically as for example devices that you find in the Bluetooth settings screen - I have to manually start the advertising of the device. So I've searched for an example and found this tutorial: Tuts+ - BluetoothLEAdvertising. With this example I've started to advertise one of the devices, and then I could find that device on another one. So, it was my bad... :)
This also means that currently the scan's result is not depending on manufacturer, API level, build version, etc... But I can imagine that these factors will possibly cause some troubles in the future...
QUESTION
I'm quite new to Android Things and Bluetooth LE Gatt. I have tried the Bluetooth LE GATT server sample provided by Google. I run the Bluetooth LE GATT server sample on Raspberry Pi 3 and the Android BluetoothLeGatt client sample on my phone. I have edit some codes in SampleGattAttributes.java and BluetoothLeService.java.
SampleGattAttributes.java
...ANSWER
Answered 2017-Apr-13 at 16:33The code you have modified from the Android Bluetooth LE client sample might be mapping to the correct Current Time UUID, but it's still attempting to parse the data as if it's a single heart rate measurement inside of broadcastUpdate()
.
The code inside that method is parsing the data fields according to the heart rate measurement spec, but the data coming from the server is a current time value. Your client code needs to parse the individual bytes out of that characteristic as defined by the Bluetooth specification for current time.
Regarding onCharacteristicChanged()
not being called, you need to verify that the server is actually receiving the subscription request. You can add logging to the server callback if you wish to see the registration happening, and the server will also log a message every time an update event is received that triggers a notification to subscribers.
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install android-BluetoothLeGatt
You can use android-BluetoothLeGatt like any standard Java library. Please include the the jar files in your classpath. You can also use any IDE and you can run and debug the android-BluetoothLeGatt component as you would do with any other Java program. Best practice is to use a build tool that supports dependency management such as Maven or Gradle. For Maven installation, please refer maven.apache.org. For Gradle installation, please refer gradle.org .
Support
Reuse Trending Solutions
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesStay Updated
Subscribe to our newsletter for trending solutions and developer bootcamps
Share this Page