我的Android應用程序應通過藍牙識別周圍是否有適當的arduino服務器。如果是這樣,應用程序將顯示敬酒消息,取決於所需的arduino服務器的存在。如果發現它應該發送關於該消息的消息,並且如果不是,則發送另一消息。在Android中使用BroadcastReceiver時無法獲得理想的吐司消息
這裏是我的代碼,當用戶按下按鈕,搜索Arduino的服務器:
public void onClick(View v) {
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
if (device.getName().equals("ARD_SPP")) {
sendButton.setVisibility(View.VISIBLE);
Toast.makeText(ConnectActivity.this, "Arduino server found, please sign up", Toast.LENGTH_SHORT);
b = true;
break;
}
}
}
mBluetoothAdapter.startDiscovery();
if (mBluetoothAdapter.startDiscovery()) {
registerReceiver(discoveryResult, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
mBluetoothAdapter.cancelDiscovery();
if (b == false)
Toast.makeText(ConnectActivity.this, "Server not found", Toast.LENGTH_SHORT).show();
}
這是裏面的BroadcastReceiver代碼:
BroadcastReceiver discoveryResult = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String deviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
if (deviceName.equals("ARD_SPP")) {
Toast.makeText(ConnectActivity.this, "Arduino server found, please sign up", Toast.LENGTH_SHORT).show();
b = true;
}
}
(我沒有把一部分的代碼約藍牙,使它更容易閱讀,認爲藍牙已經打開)
問題是,即使服務器在附近,找不到服務器的消息。因此,首先顯示「未找到服務器」,然後顯示找到服務器的消息。我不知道如何解決這個問題。
我試着用布爾變量b。我在我的代碼裏面的不同地方使用了條件,在onClick和BroadcastReceiver中,但沒有給出適當的結果。也許我沒有用好的方式使用BroadcastReceiver ...
有沒有人有想法我可以解決這個問題?它喜歡解決方案很簡單,但我不明白。
可能是這個Toast.makeText(ConnectActivity.this, 「Arduino的服務器發現,請立即註冊」,Toast.LENGTH_SHORT).show();替換爲Toast.makeText(上下文,「發現Arduino服務器,請註冊」,Toast.LENGTH_SHORT).show(); – Pavan