I can scan the Beacon in foreground using beaconManager.startScan();
so it is giving the beacons info available in the area.
same code I am using in service to scan the beacon and there also I am getting the beacon info.
But for scanning the beacon in background, I have to start the service.So is it the right practice to scan beacon using service.?
The topic of doing Bluetooth scanning in the background on Android is quite… interesting/complicated these days…
Using a background service isn't really a good option anymore. Starting with API 26 (Android 8.0), background services only continue running for a few more minutes once the user leaves the app.
(Arguably, it's not even a good option on older Androids. At Estimote, we found that some big-name Android smartphone manufacturers include their own power-management "optimizations" in their customized versions of Android, that tend to kill background services.)
You can use a foreground service, which has no limitations, but requires you to show a notification to inform the user that your app is still doing some work.
Finally, the good news is, in Android 8.0 there's a new API for Bluetooth scanning, where the BLE scan results get delivered via a PendingIntent
rather than a standard callback. This will work even if the app got suspended/terminated in the meantime.
startScan(List<ScanFilter> f, ScanSettings s, PendingIntent i)
The bad news is of course, since this is API 26 (Android 8.0) and higher, you can't really rely on it much yet, as the Android 8 adoption is still very low. The future for background BLE scanning on Android looks bright, it's just not quite here yet.
--
Naturally, if you're using a ready-made scanning lib, it's best to consult with its authors about its background capabilities and how to use them.
The https://github.com/ufobeacons/Android-SDK lib seems (at a first glance at least) not to have any background support of its own, so you're probably best off just wrapping it in a foreground service.