I am developing an app in which I will be searching for available beacons in range continuously, when the user displays a certain fragment of the app. In order to do this I created a Runnable
in which i call a method which starts a scan. Scan results are send to the Handler
using a Message
. The problem I have is that I don't know how can I call a method which would stop the scan. My code:
private class BleScanRunnable implements Runnable, BleScanCallback {
private final BleScanCallback mBleScanCallback = this;
private BleScan mBleScan =
BleScanFactory.getFactory(BleFragment.this.getActivity())
.createBleScan();
@Override
public void onScanResult(BluetoothDevice device, int rssi, byte[] scanRecord) {
Message msg = mHandler.obtainMessage();
Bundle bundle = new Bundle();
bundle.putParcelable(ARG_BLUETOOTH_DEVICE, device);
bundle.putInt(ARG_RSSI, rssi);
bundle.putByteArray(ARG_SCAN_RECORD, scanRecord);
msg.setData(bundle);
mHandler.sendMessage(msg);
}
@Override
public void run() {
mBleScan.startBleScan(mBleScanCallback);
}
}
How I start and stop the runnable:
private void startBleRunnable() {
ExecutorService threadPoolExecutor = Executors.newSingleThreadExecutor();
BleScanRunnable bleScanRunnable = new BleScanRunnable();
mBleScanRunnableFuture = threadPoolExecutor.submit(bleScanRunnable);
}
private void stopBleRunnable() {
mBleScanRunnableFuture.cancel(true);
}
The question is how can I not only stop the Runnable, but also call mBleScan.stopBleScan()
method in onPause()
method of the BleFragment
Is it OK to add such method:
public void stopBleScan() {
mBleScan.stopBleScan();
}
to the BleScanRunnable
and call it from onPause()
like this:
mBleScanRunnable.stopBleScan();