我需要在周圍區域掃描藍牙設備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
有誰知道我如何能夠正確取消所有當前和正在進行的藍牙發現?
感謝您的幫助!
P.S我需要重複該過程的原因是從附近的設備獲取新的信號強度值。