2012-03-23 199 views
0

当发现其他蓝牙设备时,我为每个找到的设备发送了2个广播。第一个是在扫描期间发送的,当完成扫描时,一次发送所有找到的设备的广播。我正在调整SDK中的BluetoothChat示例。Android蓝牙发现

这里是我的 '广播接收器':

private final BroadcastReceiver foundRec = new BroadcastReceiver() { 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     String action = intent.getAction(); 
     if (action.equals(BluetoothDevice.ACTION_FOUND)) { 

      Log.e(TAG, "--- device found ---"); 

      BluetoothDevice dev = intent 
        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 

      if (dev.getBondState() == BluetoothDevice.BOND_BONDED) { 
       availableDevices.add(dev.getName() + " (paired)"); 
      } else { 
       availableDevices.add(dev.getName()); 
      } 

     } else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_STARTED)){ 

      Log.d(TAG, "DISCOVERY STARTED"); 
      findViewById(R.id.lookup).setVisibility(View.VISIBLE); 

     } 
    } 
}; 

谢谢!

+0

我相信你正在测试你的应用程序在三星设备,仪式? – waqaslam 2012-03-23 22:11:09

+0

也许我错过了,但你的问题是什么? – 2012-03-23 22:31:32

+0

我正在测试HTC。问题是如何避免每次发现两次设备。 – 2012-03-24 06:31:18

回答

1

我保留了一系列设备。每次收到ACTION_FOUND,我都会通过设备阵列检查它是否存在。我的语法可能不对,在浏览器中输入......但希望你明白了。

我不知道你使用你的availableDevices数组,但它可能更有用,如果你是一个BluetoothDevice数组而不是字符串数组。您可以随时获取名称并检查onReceive以外的保税状态。

private final BroadcastReceiver foundRec = new BroadcastReceiver() { 
List<BluetoothDevice> BtDevices = new ArrayList<BluetoothDevice>(); 
@Override 
public void onReceive(Context context, Intent intent) { 
    String action = intent.getAction(); 
    if (action.equals(BluetoothDevice.ACTION_FOUND)) { 

     Log.e(TAG, "--- device found ---"); 

     BluetoothDevice dev = intent 
       .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
     if(!IsBtDevPresent(dev)) { 
      BtDevices.add(dev); 
      if (dev.getBondState() == BluetoothDevice.BOND_BONDED) { 
       availableDevices.add(dev.getName() + " (paired)"); 
      } else { 
       availableDevices.add(dev.getName()); 
      } 
     } 
    } else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_STARTED)){ 

     Log.d(TAG, "DISCOVERY STARTED"); 
     findViewById(R.id.lookup).setVisibility(View.VISIBLE); 

    } 
} 

private boolean IsBtDevPresent(BluetoothDevice dev) { 
    int size = BtDevices.size(); 
    for(int i = 0; i<size; i++) { 
     if(BtDevices.get(i).equals(dev)) { 
      return true; 
     } 
    } 
    return false; 
} 

};

+1

你的答案是一个解决方案,是真的,但是没有可能让BTAdapter只发送一次广播给每个设备?我用这些字符串填充ArrayAdapter以显示ListView中的可用设备。 – 2012-03-24 06:36:55

0

实际上ICS和更高版本的设备发送两个广播,一个用于查询扫描,另一个用于页面扫描。这就是为什么我们收到两次!

但我在2.3.5设备中测试了相同的代码,其中我只收到一个广播接收!它如何管理? 我们要求,个人广播查询和页面或单播!任何人都可以谈论这个!