android蓝牙发现找不到设备

时间:2013-07-03 14:19:40

标签: java android bluetooth

我有一个非常简单的活动,通过蓝牙发现其他Android设备:

public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);

     // Get the local Bluetooth adapter
    FrameLayout f = new FrameLayout(this);
    setContentView(f);
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);

    this.registerReceiver(mReceiver, filter);
     // Register for broadcasts when discovery has finished
    filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    this.registerReceiver(mReceiver, filter);

    mBtAdapter = BluetoothAdapter.getDefaultAdapter();

    // Get a set of currently paired devices
    Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();


    // Request discover from BluetoothAdapter
    Log.i("bluetooth", "about to start device discovery");
    mBtAdapter.startDiscovery();

    //start receiving stuff
    mReceiver = new BluetoothReceiver();

}

问题是在活动的onCreate()结束时调用的BluetoothRecieiver类似乎找不到和设备,虽然我在调试时在附近打开了一个:

 public class BluetoothReceiver extends BroadcastReceiver {
public ArrayAdapter<String> mNewDevicesArrayAdapter;
 @Override
 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);
         // If it's already paired, skip it, because it's been listed already
         if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
            Log.i("face", device.getName() + "\n" + device.getAddress());
             mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
         }
     // When discovery is finished, change the Activity title
     } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {

         if (mNewDevicesArrayAdapter.getCount() == 0) {
                Log.i("face", "found NOTHING!");
             mNewDevicesArrayAdapter.add("no devices found");
         }
      }
   }
}

这里有什么我想念的吗?

1 个答案:

答案 0 :(得分:0)

我认为这是因为当您致电registerReceiver() mReceiver为空时,将mReceiver = new BluetoothReceiver();移到第一个this.registerReceiver(mReceiver, filter);之上,您也可以执行以下操作:

filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);

然后只调用一次this.registerReceiver(mReceiver, filter);