我有一个非常简单的活动,可通过蓝牙发现其他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");
}
}
}
}
我在这里想念什么吗?
最佳答案
我认为这是因为当您呼叫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);