我需要对周围区域的蓝牙设备进行 6 到 12 秒的扫描。在此之后,我需要停止发现新设备。
以下代码应:
- 开始扫描蓝牙设备
- 打印出找到的任何内容
- 6秒后,取消所有发现并重复过程
问题是蓝牙发现永远不会被取消。这段代码运行一两分钟后,onReceive 将在同一秒内被调用数十次......
public void startTrackingButton(View view) {
Log.d("MAIN", "Track button pressed, isTracking: " + !isTracking);
if (isTracking) {
isTracking = false;
} else {
isTracking = true;
Thread keepScanning = new Thread(new Runnable() {
@Override
public void run() {
while (isTracking) {
if (mBluetoothAdapter.isDiscovering()) {
Log.d("MAIN", "Cancelling discovery!");
Log.d("MAIN", String.valueOf(mBluetoothAdapter.cancelDiscovery() + ":" + mBluetoothAdapter.getState()));
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
}
startTracking();
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
keepScanning.start();
}
}
private void startTracking() {
Log.d("MAIN", "Starting Discovery...");
mBluetoothAdapter.startDiscovery();
// Create a BroadcastReceiver for ACTION_FOUND
BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
Log.d("MAIN", "Device Found...");
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a
// ListView
Log.d("MAIN:",
device.getName() + "\n" + device.getAddress());
}
}
};
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister
// during onDestroy
}
这是我的 logcat 输出:
//onReceive gets called many times in the same second???
05-01 22:09:56.949: D/MAIN(3757): Cancelling discovery!
05-01 22:09:56.969: D/MAIN(3757): false:12 ///THIS SHOULD BE TRUE
05-01 22:09:56.969: D/MAIN(3757): Starting Discovery...
05-01 22:10:03.009: D/MAIN(3757): Starting Discovery...
05-01 22:10:03.579: D/MAIN(3757): Device Found...
05-01 22:10:03.579: D/MAIN:(3757): TOMSELLECK
05-01 22:10:03.579: D/MAIN:(3757): 06:07:08:09:A1:A1
05-01 22:10:03.579: D/MAIN(3757): Device Found...
05-01 22:10:03.579: D/MAIN:(3757): TOMSELLECK
05-01 22:10:03.579: D/MAIN:(3757): 06:07:08:09:A1:A1
05-01 22:10:03.589: D/MAIN(3757): Device Found...
05-01 22:10:03.589: D/MAIN:(3757): TOMSELLECK
05-01 22:10:03.589: D/MAIN:(3757): 06:07:08:09:A1:A1
05-01 22:10:03.589: D/MAIN(3757): Device Found...
05-01 22:10:03.589: D/MAIN:(3757): TOMSELLECK
05-01 22:10:03.589: D/MAIN:(3757): 06:07:08:09:A1:A1
05-01 22:10:03.589: D/MAIN(3757): Device Found...
05-01 22:10:03.589: D/MAIN:(3757): TOMSELLECK
05-01 22:10:03.589: D/MAIN:(3757): 06:07:08:09:A1:A1
有人知道我如何正确取消所有当前和未决的蓝牙发现吗?
谢谢你的帮助!
PS 我需要重复该过程的原因是从附近的设备获取新的信号强度值。