DZarrillo
DZarrillo

Reputation: 31

Automatically have an Android device connect & receive advertised data from BLE device

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?

Upvotes: 1

Views: 1075

Answers (1)

OnJohn
OnJohn

Reputation: 348

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.

  1. Start the service on app start
    This is the starting point of your service first run. Just call startService in your activity onCreate.

  2. Keep service running
    See, how to keep service running

  3. 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

  4. Start the service on device boot
    See, start service at boot

  5. 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.

Upvotes: 2

Related Questions