Android Bluetooth Low Energy Guide (Connect to a BLE sensor) - Android Studio Tutorial with Kotlin

  Переглядів 25,382

K Apps

K Apps

День тому

In this tutorial I will show you how you can connect to a BLE sensor/device from your Android Applikation using Android Studio and Kotlin. We will build a simple UI which refreshes every second to update the values retrieved from a BLE sensor. You will also see how to properly handle all necessary permissions and check for the Bluetooth state during runtime.
00:00 Introduction
01:51 Dependencies
2:42 Navigation and first screen
22:20 BLE Service
1:04:58 Viewmodel for state management
1:13:32 Final screen for updating BLE values
Initial project:
github.com/MatthiasKerat/BLET...
Final project:
github.com/MatthiasKerat/BLET...

КОМЕНТАРІ: 84
@mostafahosseini2944
@mostafahosseini2944 Рік тому
Thanks for the tutorial, very good job👍
@SiamakAshrafi
@SiamakAshrafi Рік тому
The best tutorial on the subject
@kapps7407
@kapps7407 Рік тому
Thank you!
@mattdyor7267
@mattdyor7267 9 місяців тому
Great video, Matze! Which sensor are you using? Looks like a pretty small one that you could just tuck into a corner pretty easily. Appreciate you taking the time to make this video - covered a ton of ground!
@hightechif4369
@hightechif4369 Рік тому
Thanks for the tutorial
@ericksagaguara
@ericksagaguara Рік тому
Niceee thank you for this tutorial!
@justoaguiar2514
@justoaguiar2514 10 місяців тому
Thank you, it was a great help.
@simonwambua3710
@simonwambua3710 Рік тому
Thank you for this 🤟🏾
@Lingchao2596
@Lingchao2596 3 місяці тому
Great video. Thank you.
@inteluxintelux4222
@inteluxintelux4222 Рік тому
Nice tutorial. Please make tutorial on BLE mesh using Android.
@GN9K71
@GN9K71 8 місяців тому
Great video. Only one remark: you can use callback flow to wrap the callbacks, instead of launching coroutine every time a callback is invoked.
@nishithpandya2629
@nishithpandya2629 Рік тому
thanks for the video, learned so much in one video, could you please try to make video with wifi also
@khynantoque
@khynantoque Рік тому
Superb tutorial. I do have a question, how do you get the Major, Minor, and the TxPower or RSSI from the BLE, is it the same from getting the temperature and humidity?
@kapps7407
@kapps7407 Рік тому
Thank you! You can get the TxPower and RSSI in onScanResult from the ScanResult itself which is a readable form of the advertising package. Minor and Major are also part of such an advertising package. But iBeacon where the Major and Minor is included is just a standard that bases on BLE but not every BLE device has this iBeacon standard. So the Android Bluetooth classes does not provide a minor and major property since it is not always there if a BLE ScanResult comes in. I never needed to access these two values but maybe you have to use some third party library
@lorenzolastrucci6790
@lorenzolastrucci6790 Рік тому
Hi, thank you for the tutorial. I would like to import your project on my pc and do some mods. I tried first to export the apk of your project but it's not working the same way. I see that there are some missing files uploaded in the github folder(not sure about that). Can you help to import correctly the project on my PC?
@Ayushkumar-pu9ni
@Ayushkumar-pu9ni Рік тому
Hey Amazing tutorial, i have a question. I am new to kotlin jetpack and i am currently working with a similar app with kotlin jetpack compose and I need to connect my application with an HC-05 Bluetooth module, how should I change this code to fit my application, or is there any source that can help me? Can you please help me as I am unable to find any good resource.
@SharifJohnGhafforov
@SharifJohnGhafforov Місяць тому
Hello Sir ! I liked your work. Thanks ! I have a question: Do we need any kind of data from Device with BLE to be able to connect and share data with it ?
@afaqurrehmankhan3133
@afaqurrehmankhan3133 8 місяців тому
You showed us an example of how to read values from the BLE device. Weren't you reading from the BLE Device already?
@alexkokos5363
@alexkokos5363 Місяць тому
Great video, thank you for your job! Can you help me please? May i connect Tuya BLE THB2 sensor using this app, the fact is that when ble sensors are scanned, it does not see them, although these sensors are ble devices :(
@kevinmartinez2215
@kevinmartinez2215 28 днів тому
Hi there, do you have an example to read the characteristic ?
@MyHobbies-qh8pg
@MyHobbies-qh8pg 4 місяці тому
hi Sir, thank you for the best tutorial, is it possible to create another tutorial where we actually write to Arduino or Esp32 to control a simple LED to turn ON and Turn Off?
@androidble6262
@androidble6262 Рік тому
einfach Klasse , ich finde du hast viele Mühe für BLE gegeben. Darf ich fragen wie heisst dieser Sensor?
@kapps7407
@kapps7407 Рік тому
Danke! Das war dieser hier: JINOU Bluetooth Low Energy 5.0 Beacon/iBeacon mit Sensor, kabelloser Feuchte- und Temperatursensor. Für Android/iOS
@xxzmk
@xxzmk 11 місяців тому
To what part of this video do I need the code ? I only want to write Gatt Characteristics to a BLE ESP32 Module
@user-fh4mv8pl2g
@user-fh4mv8pl2g 3 місяці тому
do you know what bluetooth chip the sensor uses? I'm trying to do a similar project with a HM-10 chip! Thanks
@jibinjayachandran9922
@jibinjayachandran9922 9 місяців тому
Thanks for the Video .. its so amazing.❤ It helped me for implementing with weight scale in android app. As I don’t have any device name , i added a filter with service_uid and I used the same descriptor_uid as as in your code and it works fine..😊 But when I convert the byte array to my weight , I had to convert the byte to toUInt to get the proper value upto some extend.. after that I’m getting incorrect value in the byte array.. Could you please suggest something on this ?
@marcelonapoleao6347
@marcelonapoleao6347 9 місяців тому
did you get his code to build or did you code your own version along with him? I was trying to follow this but after following his steps to add dagger hilt and even cloning his finished project it just won't give me a successful build no matter how i try to fix the gradle file. any suggestions?
@HappyPhone-wj2dc
@HappyPhone-wj2dc 8 місяців тому
Can you help me how to build his original version? With Giraffe version of Android Studio, I have the following build error. e: This version (1.1.0-beta01) of the Compose Compiler requires Kotlin version 1.5.31 but you appear to be using Kotlin version 1.6.21 which is not known to be compatible... So I changed build.gradle file as follows: buildscript { ext { // compose_version = '1.1.0-beta01' compose_version = '1.2.0-rc02' } It compile and build OK. App appears OK but at BLE scanning stage, it stuck and did not show any avaiable device.. Your help will be greatly appreciate..
@brendonshaw6412
@brendonshaw6412 Рік тому
This is a outstanding tutorial well done, I am having problems with the BLE reading and no call back is been triggered. I added your example code, odd in the logcat there is no debug commands for any ble read. I have similar code running in Java and I can see the BLE triggers. When the app starts it triggers the call back onCharacteristicChanged and it get the data on mobile app start up. But, doing a manual read does not trigger this call back.
@brendonshaw6412
@brendonshaw6412 Рік тому
I found the problem, which was really odd. The call backs were in the wrong place, onCharacteristicRead should be at the end of the main code block. I delete this function onCharacteristicRead, then it reported an error and then auto added the function back into the right location.
@KenFuzion
@KenFuzion Місяць тому
@@brendonshaw6412 can i see your code, if you don't mind? my app gets stuck at ""Could not find temp and humidity publisher"
@alexkokos5363
@alexkokos5363 Місяць тому
@@KenFuzion Did you manage to fix this?
@KenFuzion
@KenFuzion Місяць тому
@@alexkokos5363 nope
@faridbenhaimoud8294
@faridbenhaimoud8294 Рік тому
Nice tutorial!! Do you know a way to clear the gatt table?
@kapps7407
@kapps7407 Рік тому
Thank you Farid, what do you mean by that?
@faridbenhaimoud8294
@faridbenhaimoud8294 Рік тому
@@kapps7407 Well I have an app that can update firmware via BLE. But now I have updated the device with a firmware that corrupted the uuid's so I have to clear the gatt table and refresh the services. But I can't think of a nice way to do it.
@kapps7407
@kapps7407 Рік тому
Sorry I don't know if there is a solution from Android side since its related to your firmware and I am not that deep into configuring embedded systems.
@Babs_i
@Babs_i 2 місяці тому
SOS! First step- first Problem! compose_version and classpath are red, Gradle sync failed. Is there anything I should have done before? How did you all do this?
@jbharatrhodes1
@jbharatrhodes1 Рік тому
Really nice tutorial. Is it possible to have a multiple devices connected to the same app ?
@kapps7407
@kapps7407 Рік тому
Thank you! Of course you can. When you get your scan results then just start the connection for all devices you want (Or list them to the user first and connect via click on the specific devices). Inside your gattCallback functions you can then check the devices address or name on the received gatt for example to check which connected device is currently triggering the callBack function. I would save the received gatt of each device after connection in some kind of array data struct like List at the beginning to make the device management comfortable.
@jbharatrhodes1
@jbharatrhodes1 Рік тому
@@kapps7407 I was able to connect two similar devices but can get data from only one. Does BLE support data retrieval from multiple devices simultaneously?
@kapps7407
@kapps7407 Рік тому
Yes you should be able to retrieve them. When you establish the connection to those devices then you need to save the gatt somewhere with a corresponding ID or something like this to differentiate later which gatt belongs to which device. And then in your onCharacteristicChanged() Callback you will get a gatt and need to check which gatt it actually is. If you just want to check if the retrieving of both devices works then just connect to them both subscribe to the right characteristics and then in your onCharacteristicChanged both values should come. But be careful when you connect and subscribe to both devices always do it step by step and not two commands at once.
@jbharatrhodes1
@jbharatrhodes1 Рік тому
@@kapps7407 thanks. I was able to connect multiple devices and retrieve the data, however, the auto-reconnect function is not working? Does auto-reconnect works for multiple device?
@kapps7407
@kapps7407 Рік тому
Do you mean the autoConnect Boolean which you pass in the connectGatt(..) function?
@pedroriva2880
@pedroriva2880 10 місяців тому
Thx for this contribution! I am getting troubles perhaps you can help me... I added 2 notifyble characteristics on a first service and 1 more notifyble characteristic on a second service. So 3 notyfiable charactics total. I have used enablenotification three times with each charact uuid without errors it seems all to be ok from app point of view ( I verifyed is ok and three different descriptor adresses) but only the first one change the descriptor on server.. any suggestions? writeDescription function needs anything else? It is not reporting error but I am verifying on two devices and with nRF app only the first descriptor is enabled on server..
@pedroriva2880
@pedroriva2880 10 місяців тому
If you need more descritions or the modified code please let me know
@pedroriva2880
@pedroriva2880 10 місяців тому
Update: if I change the order wnen using enableNotification function ever the first is enabled but not the other two characteristics.. perhsps needs time between descrptor writes?
@pedroriva2880
@pedroriva2880 10 місяців тому
Ok.. it seems clear i am missing to wait the writeDescriptor to finish properly. As a newbie I am still struggling with basics
@lucasianii8178
@lucasianii8178 7 місяців тому
Hi sir, i need some help on my code, how can I reach you?
@jayveegonzales1988
@jayveegonzales1988 Рік тому
hello just a question is that possible to monitor multiple BLE devices?
@kapps7407
@kapps7407 Рік тому
Yes sure it is !:) you can have multiple gatts. For each ble one
@Liam-vn2tr
@Liam-vn2tr Рік тому
To anyone getting this error: java.lang.SecurityException: Permission Denial: starting Intent { act=android.bluetooth.adapter.action.REQUEST_ENABLE cmp=com.android.settings/.bluetooth.RequestPermissionActivity } from ProcessRecord{5ba8236d 124:com.example.appname/u0a155239} (pid=321, uid=2314) requires android.permission.BLUETOOTH_CONNECT As of android 6.0 some permissions have to be requested at runtime so it's not enough to put the permissions in the manifest anymore. This tutorial gives more info - ukposts.info/have/v-deo/sGNpmI-MpG2lpI0.html&ab_channel=AndroidDevelopers
@chiragredij1734
@chiragredij1734 7 місяців тому
Im stuck in currentlyInitializing state which keeps scanning for my device. I have changed the Service and Characteristics Uuid as per my device but there is no progress. I don't use compose so Im using button to trigger the scan. I would appreciate if you can help me with this. Thank you regardless.
@chiragredij1734
@chiragredij1734 7 місяців тому
hey! So actually I got past the scanning stage but now I cant figure out how to get data properly... Im using a proxy device from the an App to replicate BLE... I can connect to it but I cannot figure out how to retrieve the data I want - "BLE Scanner" the apps name. If know anything about how to do that... I will be appreciated
@emelienordin1488
@emelienordin1488 Рік тому
Is it possible to see the arduino code you are using? I am having trouble with the communication between app and arduino :)
@kapps7407
@kapps7407 Рік тому
Hi Emelie, sorry no I don’t have the code I just bought that sensor on Amazon ..
@mwigojonathanmark1683
@mwigojonathanmark1683 Рік тому
Followed the tutorial well, but my application is stuck in "Adjusting MTU" it doesn't go past that. Tried changing to many Service IDs and Characteristic ID. Any help?
@MohannadHaddad3
@MohannadHaddad3 10 місяців тому
I am stuck there as well, aby updates?
@mwigojonathanmark1683
@mwigojonathanmark1683 10 місяців тому
@@MohannadHaddad3 not really, haven't yet figured it out... I dropped the future for a later release when I get the Bluetooth part figured out
@gabrielz2241
@gabrielz2241 6 місяців тому
Any updates? About month ago i resolved it then today i checked the feature again and its not working... shame me i could write down what i have changed@@mwigojonathanmark1683
@teepakorntosak7770
@teepakorntosak7770 11 місяців тому
(my own progress timestamp) 22:10
@masterkey1831
@masterkey1831 9 місяців тому
i downloaded the "BLE scanner" on my android phone and it shows so many "mac addresses" and someone said it is people who took the jab. i went to walgreens since they give the jab there and i got over 200 "BLE mac addresses" when no one was in the store by the pharmacy. is it true it is the people who took the jab?
@siva_subramaniam
@siva_subramaniam 10 місяців тому
bm - 22:09
@PandaTop.
@PandaTop. Рік тому
Hi! . How to connect to a smartphone using bluetooth?
@kapps7407
@kapps7407 Рік тому
Create a classic Bluetooth socket connection between both Smartphones and then you can use an input and output stream for communication :)
@PandaTop.
@PandaTop. Рік тому
@@kapps7407 Thanks :)
@ryusuikagaku
@ryusuikagaku Рік тому
my app got stuck on "adjusting mtu space", can you help me
@kapps7407
@kapps7407 Рік тому
What exactly do you mean by "got stock"? That the "onMtuChanged()" callback does not get triggered?
@ryusuikagaku
@ryusuikagaku Рік тому
@@kapps7407 i think thats the problem, because when i run it, it always showing loading icon and text "adjusting mtu space"
@kapps7407
@kapps7407 Рік тому
Difficult to say without seeing your code. But you can try to leave the requestMtu() command away and just subscribe directly to the notification inside the onServiceDiscovered() callback. Make also sure that you don't execute two commands in the process line at once. They need to be executed after each other.
@simonandersson1729
@simonandersson1729 Рік тому
@@kapps7407 I also have the same problem where the app is "stuck" on "adjusting MTU space". I'm using the same code but have made the change from having two inputs to one. Where in the code can I check if the commands are executed after each other? Great video, thank you for all the help!
@kapps7407
@kapps7407 Рік тому
@@simonandersson1729 You can apply logs on different positions to check what gets executed when. I recommend you to implement some kind of execution queue which assures that everything happens step by step. But logs should already help I think
@HappyPhone-wj2dc
@HappyPhone-wj2dc 8 місяців тому
Can you tell me which version of Android Studio used in this example? I have a running error using current version of Android Studio. Your help will be appreciate in advance. Error is as follows: :app:kaptGenerateStubsDebugKotlin java.lang.IllegalAccessError: class org.jetbrains.kotlin.kapt3.base.KaptContext (in unnamed module @0x52a8bf8b) cannot access class com.sun.tools.javac.util.Context (in module jdk.compiler) because module jdk.compiler does not export com.sun.tools.javac.util to unnamed module @0x52a8bf8b
@cb45yo29
@cb45yo29 8 місяців тому
I am also getting the same error when attempting to test the app for the second time. (Meaning at around 14 mins when you do)
@vaurelalghanieputra3403
@vaurelalghanieputra3403 4 місяці тому
did u figure it out yet? i am also getting the same error.
@octotech91
@octotech91 3 місяці тому
You have to update the Kotlin Gradle Plugin Version. Plus, you might have an error of incompatibility with your compose compiler, in that case you have to update the compose compiler version number in the "build.gradle" file accoridng to your Kotlin version (if you don't know which one to choose google "Compose to Kotlin Compatibility Map")
Master BLE Basics in Just 10 Minutes: The Ultimate Guide!
9:15
Novel Bits
Переглядів 85 тис.
MVVM vs. MVI - Understand the Difference Once and for All
18:40
Philipp Lackner
Переглядів 19 тис.
«Що ви тут лазите?». День з військовими ТЦК Києва + ENG SUB
24:04
Слідство.Інфо | Розслідування, репортажі, викриття
Переглядів 301 тис.
This 14 year old MacBook has some features M1 could only DREAM of.
8:56
What's on Your Screen?
Переглядів 14 тис.
Simmerstats: The genius old tech that controls your stovetop
36:31
Technology Connections
Переглядів 702 тис.
Разбираем основы Kafka и RabbitMQ
26:54
Digital train | Alex Babin
Переглядів 2,3 тис.
Fundamentals of Compose Layouts and Modifiers - MAD Skills
11:56
Android Developers
Переглядів 77 тис.
React-Native with Expo and Bluetooth Low Energy for Beginners
20:02
Dan's React Native Lab
Переглядів 35 тис.
Back when the internet was fun. (1999 Apple iBook)
22:46
DankPods
Переглядів 381 тис.
Building Android Apps to Control Bluetooth LE Devices
38:51
CrossComm, Inc.
Переглядів 34 тис.
Easiest ESP32 BLE (Bluetooth Low Energy) Tutorial | Arduino
11:28
LiveSparks
Переглядів 90 тис.