我正在开发一个应用程序,当用户显示应用程序的某个片段时,我将在其中连续搜索范围内的可用信标。为了做到这一点,我创建了一个Runnable
在其中调用开始扫描的方法。扫描结果Handler
使用Message
. 我遇到的问题是我不知道如何调用可以停止扫描的方法。我的代码:
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);
}
}
我如何启动和停止可运行文件:
private void startBleRunnable() {
ExecutorService threadPoolExecutor = Executors.newSingleThreadExecutor();
BleScanRunnable bleScanRunnable = new BleScanRunnable();
mBleScanRunnableFuture = threadPoolExecutor.submit(bleScanRunnable);
}
private void stopBleRunnable() {
mBleScanRunnableFuture.cancel(true);
}
问题是我怎样才能不仅停止Runnable,而且在方法中调用mBleScan.stopBleScan()
方法onPause()
BleFragment
添加这样的方法是否可以:
public void stopBleScan() {
mBleScan.stopBleScan();
}
到BleScanRunnable
并这样调用它onPause()
:
mBleScanRunnable.stopBleScan();