I am doing an APP to configure/control battery powered devices using Bluetooth.
The devices are not "visible" to save energy.
I have a ready list of about 50 device. The list contains the Bluetooth MAC address and the required PIN to pair.
When the APP starts up, I prompt the user to select a device from the list.
So now I want to automatically bind with the device, if not already done yet, without the need for the user to enter the PIN again.
I googled a lot, but did not exactly find what I was looking for (at least what I understood).
But I have to admit that I am pretty new to android programming and might simple not get the hint-
I also assume I do not use the right terms to search.
I found some "hacks" that simply suppress the PIN entry.
Can someone help me out here?
I already had the APP up and running if I manually bind the device, so the SPP communication is not the problem, it's mainly how to provide the PIN for connection.
Thanks a lot.
You can create new bond with bluetooth device by calling BluetoothDevice setPin(byte[] pin) and createBond() methods. You need also set BLUETOOTH_ADMIN permission.
public boolean createBond ()
public boolean setPin (byte[] pin)
Related
I'm developing an android BLE app in which i try to establish a stable Connection between the app and a BLE device.
To achieve this i want my app to keep the BLE device data in shared preferences or somewhere.
After app close, i'd like my app to retrive this data and attemp a connection without scan for devices.
I prefer to avoid scanning every time becouse scan gives me a lot of problems and it takes time.
How can do it? Is there a way to save BLE data?
You need to store the Bluetooth Device Address (AB:CD:EF:01:02:03) of the device in for example shared preferences or in a sqlite db. Then use https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#getRemoteDevice(java.lang.String) when you later restart the app to retrieve a BluetoothDevice object. Once you have the BluetoothDevice object you can use the connectGatt method as usual.
There are some undocumented things you need to keep in mind however. Due to some horrible design flaws in Android's BLE API there is no way to tell it if you mean the given address is a Public Address or a Random Address. (You can read more about different address types at https://devzone.nordicsemi.com/question/43670/how-to-distinguish-between-random-and-public-gap-addresses/). The getRemoteDevice method should take an additional parameter "random address/public address" but it doesn't. Without the correct address type, the Bluetooth controller cannot connect to the device.
Android's BLE stack has some internal heuristics to "guess" if the address is public or random, but unfortunately that differs between Android versions and also if you use autoConnect=true or false. However if you have bonded the device (https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#createBond()) then it will store in its internal DB whether the given address is public or random. If the peripheral you want to connect to uses a random resolvable address it can handle that as well if you use bonding. Therefore I strongly suggest to use bonding.
If you don't use bonding you will need to scan before you connect to the device, since when you start a scan and a device is detected, Android's BLE stack will temporarily (until next restart of Bluetooth) remember the address type for an address.
I will continue on Emil's answer.
Thanks #Emil for the 'big picture'.
Google API is flawed and you can't use getRemoteDevice() because it only understand 48bit address and do not know about all BLE address types.
You can't use Bonding if the device is dumb (anyone would be able to bond to it).
So your only solution is a Bluetooth scan.
However, since Android6 (Marshmallow) the user has to give location permission to apps using Bluetooth scanning. If you don't permit, it won't work.
So if you buy a Bluetooth thermometer (or heart-rate monitor or whatever), you have to permit the app to access location of your phone (or tablet).
That's absurd!
#Emil call it a 'Google flaw'. You may also call it a 'Google machination'.
If I was a thermometer designer, I would add a push-button to accept bonding. It seems ridiculous because the button will only be used once.
[1]: https://www.polidea.com/blog/a-curious-relationship-android-ble-and-location/
What I want to know:
I'm wondering how the android system (like Android smart phone) auto-connects to devices which is paired before.
For example, I pair my bluetooth headset with my android smartphone in the procedure of "turn on scanning/advertising -> click pairing" on day 1. And when I turn on advertising on my headset, it connects automatically on day 2, 3, 4, and so on. The point is, I don't have to make my smartphone scan again to find my (paired) headset.
I can't understand how android system finds that the paired device is turned on. Does the android system scan periodically in background? Even if I don't click "scan" button?
Why I ask:
I want to make my app autoconnect to customized BLE device, after make pairing. I succeed to make pairing(bonding) with createBond() method, but after that, I couldn't find how to make autoconnect. I know I can turn on autoconnect function like this way, connectGatt(XXX, true, XXX), but this autoconnect function doesn't work when the BLE device is disconnected a few days.
So I want to make my app works like android system and Bluetooth headset. But I couldn't find how android bluetooth system works even I dig AOSP codes.
I found many questions (here and here) about problems like mine but there were no answers.
Thanks in advance.
Update:
I found that bt_btif gets activated (with LG smartphone and Nexus 5) when the paired headset is turned on (start advertising). But bt_btif doesn't get activated with my custom BLE device... What can I do?
Executing connectGatt(XXX, true, XXX) is the correct way to go. gatt.connect() also starts an auto connect. Once you execute that, your phone will scan for the device and once it appears it connects to it. The only thing that interrupt this call is either if Bluetooth is turned off on the phone or if your app process is being killed. To avoid your process from being killed, let your app have a foreground service.
One gotcha however, there is a bug in Android which will sometimes make auto connect do a direct connect instead (and cancel after 30 seconds or so). See https://code.google.com/p/android/issues/detail?id=69834. You need to use reflection to avoid this bug.
I think I found a solution.
First, the solution for my question: Android smartphone seems to detect state changes of nearby bluetooth devices from the hardware sides. When the paired bluetooth headset starts to advertise, a callback in HAL (I think) is called.
So I made my app to connectGatt with autoConnection=True to the device that I want, by using MAC address, when the activity is started (in onResume() of MainActivity).
The connection would fail if my BLE peripheral device is not advertising. But the device auto-connects when it starts advertising, because the autoConnection parameter was set to true.
I've done a similar app and i didn't have problem with that. As a last resort for your problem, i would suggest writing the BLE Device Address in a simple DB table and manually connect to it. I've made something like this here
. It is no best practice code, but i hope you can find ideas for you solution.
Is there any simple way to check if an existing BluetoothDevice object is still reachable without performing a new scan?
I am writing an app that scans for devices and goes through connecting to each one at a time to populate a device list with some information about each device, which I acquire while connected to the device. Every now and again, I would like to go through my device list and remove any devices that are no longer active/in range. What is the best way to do this?
You could try to connect to the devices to find out if they are still around, but keep in mind, that devices will change their mac address from time to time.
I would suggest to use scanning to find out if the devices are still around. Also you may want to add an identifier into the advertisement packages, so you don't need to relay on the mac address.
I am developing an application which connects devices over bluetooth and exchanges messages. It works fine for paired devices, but I would also like it to automatically pair devices that are not paired. Like for example it could store and use the same PIN for pairing requests, I just dont know how to manage this request programatically in my applciation, how to automatically set and send the PIN when you get a pairing request and how to initiate such a request with the predefined PIN code.
Any snippets or thoughts would be highly appreciated! :)
EDIT:
I know its risky, I am developing this app for emergency situations only where no other means but bluetooth is available. Also is there maybe a way of premature pairing with devices without even connecting to them? Like lets say there is a list of MAC Addresses of those devices and I can use them to generate a bond with that devices so that they appear paired on my device?
You can't do this. To do what you want to do would create a huge security risk. Think about it, my device just comes anywhere in bluetooth range of yours and now I can send you anything I want without you knowing? You can't really do this and I highly recommend not trying to subvert it.
Reflecting the setPin method allowed me to send the pin automatically to the other device. I had to implement it in a broadcast receiver that is listening for pairing requests. Although I cant get rid of the dialog it just stucks there on the screen and I dont know how to close it (programatically) and continue the bonding procedure since this dialog is called from inside connect() which is a blocking method. I am not giving up on it yet though :)
With Bluetooth version 2.1 and above there is a method of pairing called the 'just works' association model. This is the lowest security method of pairing and has no protection against man-in-the-middle attacks.
However, this will provide a secure, encrypted link without the need to exchange pin numbers or verify device ID.
The API on different platforms may differ but the underlying HCI messages require that you indicate that your device (or one of the devices) has the following IO capabilities:
No Keyboard, No Display.
As you might have guessed, this is a mode for very
simple devices that use Bluetooth, such as a speaker or headphones.
If you can find the API to configure that, then the 'just works' association mode of Secure Simple Pairing will be used for pairing.
The next step is to store the link keys e.g. bonding. Many devices e.g. mobile phones, will still create a dialogue box to the user to ask if they want to 'remember this device', as user authorisation is specified by the BT specifications... but that's another problem.
I was reading this
http://developer.android.com/guide/topics/wireless/bluetooth.html#QueryingPairedDevices
which is allot of help on how to pair,connect to a bluetooth device.
I have a situation where I have several BT devices that are in Non-Discover mode always. I know the MAC and the PIN of these devices. IS there a way in Android Dev to manually add devices to the PAIRED list so i can just use the connect as a client.
I understand this maual is written allot for V3. i think i will need to do this on 2.0 ; 2.1- has anybody done this before?
Basically these devices I want to connect to are power saving modules I used pre built BT modules to monitor daylight, another one humidity, etc.. every 3hrs or when interrupted and runs of a single battery for months. So turning off divcory on server saves immense power and prevents other people trying to connect and waste battery.
Not sure what you mean by "manually": Do you mean "manually" as in GUI/user interaction, or "manually" as "I do it in my own application code"?
Some suggestions though:
If you can make your BT devices discoverable at all, you could do it this way:
Make your BT device discoverable
Let Android search for and find the device and then initiate a connection
Android will ask for the PIN for pairing with the device; enter the PIN.
Once pairing was successful, Android stores the pairing information for future use, so that you can
Make your BT device invisible again.
From then on your app should be able to connect to the BT device at any time without further pairing operations.
If the said is not an option for you, maybe you want to go another way:
In current Android versions there are different API routines implemented which are neither documented nor exposed in the normal SDK. A hack kind of solution may be to use some of these "hidden" ("#hide"...) APIs, either via reflection or via modification of your SDK installation.
But be aware that this is always a hack and it may work on a specific device with a specific version of Android and is likely to break your app on another device and/or any other Android version.
Having said that, here comes some reference:
Example of how to access "hidden" bluetooth API.
Then, have a look at the source code for android.bluetooth.BluetoothDevice, e.g. here.
In there, public boolean createBond(){...} may do what you want.