I am working on the distance estimation of BLE Beacons from the Android phone. I have developed my own algorithms for distance estimation based on RSSI. (I shall roll out the distance calculation algorithms in the form of a library soon). For calculations, phone needs a huge number of advertisement packets from the beacons around.
So far, I have tested the code with normal practices for BLE scanning. As of now I have written the code for target API Level 19. Following is a part of the code I am working on, where I start the scan for beacons and stop it after 10s.
private void scanLeDevice(final boolean enable) {
if (enable) {
handler.postDelayed(new Runnable() {
@Override
public void run() {
bluetoothAdapter.stopLeScan(LEScanCallback);
}
}, 10000L);
bluetoothAdapter.startLeScan(LEScanCallback);
}
}
private BluetoothAdapter.LeScanCallback LEScanCallback =
new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice bluetoothDevice, int rssi, byte[] scanRecord){
display(rssi);
//append to an arrayList for further processing
}
};
Currently I am doing most of the things on UI thread.I have to achieve the functionality in the following way by creating more threads.
- UI Thread should be kept free of all the calculations or LeScans.
- PacketReaderThread - A separate thread for scanning packets and keep appending them to an arrayList (I will wipeout unnecessary data from arrayList upon its consumption in algorithms). Rather than stopping the scan after certain time, I want to keep the scan ON for infinite time to keep working in real-time, as far as app is running. So I might use IntentService for this.
- DistanceCalculatorThread (or AsyncTask)- ArrayList object(containing scanned packets) will be synchronized between this and the PacketReaderThread for taking/wiping-out data packets and inform about distance calculation to UI.
I saw the implementation of BluetoothAdapter.LeScanCallback on Grepcode I have following questions.
- Is BluetoothAdapter.LeScanCallback implicitly bound/tied to main/UI thread or is it portable to any other thread ?
- If I move both of the implementations of the code above to some other thread, will the callback work on that thread or is it going to be bound to main/ui thread ? (Since I need packet scanning on separate thread, I need to know about bluetoothAdapter.startLeScan(LEScanCallback) and BluetoothAdapter.LeScanCallback)
(Note - I have already followed this question, in that question, the answer-seeker himself states that callback is on main thread, so I didn't get the actual answer. Also I saw altBeacon specs and studied their reference app, it also uses CycledScan mechanism with scan-stop-scanAgain way)