我有一个非常简单的活动来通过蓝牙发现其他 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");
}
}
}
}
我在这里有什么遗漏吗?