![](/img/trans.png)
[英]Apart from intent is there any other way to send data across activities in android studio
[英]Is there any other way to discover Bluetooth apart from using BroadcastReceiver?
我已經在服務中為BluetoothDevice.ACTION_FOUND創建了BroadcastReceiver,以掃描和記錄可用的Bluetooth設備。 該服務的一部分是每30秒檢查一次以前找到的藍牙設備是否仍然可用。 目前,它為我的Leaked IntendReceiver引發了一個錯誤,我可以修復該錯誤,但是我只是不確信這是正確的方法。 我正在創建一個新線程來處理藍牙掃描,創建了一個每30秒運行一次的while循環,並在該循環內注冊了BroadcastReceiver,使線程進入睡眠狀態,直到睡眠時間超過onReceive時,我才能得到當前掃描的結果,然后我取消注冊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
}
}
};
弄清楚了。 沒有其他方法可以實現這一目標。 為了控制性能,我現在只注冊一次接收器,然后在睡眠間隔為60秒的循環內啟動發現。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.