I have created an android application using android studio API 21 to scan & connect to a BLE device and subscribe to receive advertised data. This works great, but now I would like to do this automatically without having the user to manually run the android application. Is there a way for my android device to know when it is in range of the BLE device and to automatically connect and receive data if available? I'm just a little confused as to what code is needed in the Broadcast receiver class and does the Broadcast receiver class need to be in a service?
1 Answers
AFAIK, there is no such system broadcast for notifying BLE device found.
I think you will have to do it by yourself with a service
To scan BLE devices in background, you will have to run the scanning in a service.
Few requirements you may want.
- Start the service on app start 
 This is the starting point of your service first run. Just call startService in your activity onCreate.
- Keep service running 
 See, how to keep service running
- Stop BLE scanning on bluetooth disabled 
 It is meaningless to keep scanning while bluetooth disabled by user.
 So, you may want this check. See, detecting bluetooth change
- Start the service on device boot 
 See, start service at boot
- Implement BLE scan in service 
 Move all the code from your scanning activity (or fragment) to the service. Something like,- BLEScanningService extends Service { @Override public int onStartCommand (Intent intent, int flags, int startId) { if (/*Bluetooth is available*/) { /* Do BLE scan */ } else { // Stop BLE scanning and stop this service } } }
Then, your will have BLE scanning service always running in background :)
Maybe you may also want to broadcast some event from the service so that app UI and notification can update correspondingly.
- 
                    thxs for the feed back. I'm going to do a little more research on when two devices are paired - bonded, to see if anything is triggered when they get into and out of range. – DZarrillo Dec 29 '15 at 04:08
 
     
    