我已經在服務中爲BluetoothDevice.ACTION_FOUND創建了一個BroadcastReceiver來掃描並記錄可用的藍牙設備。如果以前找到的任何藍牙設備仍然可用,則該服務的一部分是每30秒繼續檢查一次。目前它給我發泄一個錯誤,我可以修復這個錯誤,但我不確定這是否是正確的方法。 我正在創建一個新線程來處理藍牙掃描,創建一個每30秒運行一次的while循環,並在該循環內註冊BroadcastReceiver,將線程置於睡眠狀態,到睡眠時間結束時,onReceive會給出當前掃描結果,然後我取消註冊BroadcastReceiver並重復循環。除了使用BroadcastReceiver之外,是否還有其他方法可以發現藍牙?
我在while循環的每一次完成後取消註冊BroadcastReceiver,因爲下一次掃描會給出當前可用設備的列表,然後將其與之前掃描的數據進行比較。
它符合我的要求,但是我有強烈的感覺,它不是正確的設計。你能否以另一種方式給我建議?謝謝..
下面是從服務 -
class ScanBT extends Thread
{
static final long DELAYBT = 30000;
@Override
public void run()
{
isBTRunning = true;
Looper.prepare();
BluetoothAdapter mBluetoothAdapter =BluetoothAdapter.getDefaultAdapter();
try {
Log.d(TAG, "BT Scanning started");
while(isBTRunning)
{
if (!mBluetoothAdapter.isEnabled())
{
mBluetoothAdapter.enable();
Thread.sleep(15000);
}
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
mBluetoothAdapter.startDiscovery();
Log.d(TAG,"Inside while loop for BT");
Thread.sleep(DELAYBT);
unregisterReceiver(mReceiver);
}
Looper.loop();
}
catch (InterruptedException e) {
Log.d(TAG, "BT Scanning stopped");
Looper.myLooper().quit();
}
}
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
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);
BTDevice = device.getName();
BTAddress = device.getAddress();
Log.d(TAG,"BT Found name: " + BTDevice);
Log.d(TAG,"BT Found address: " + BTAddress);
//Code to compare with previous scan results
}
}
};