我是 Android 编程新手。我想制作一个包含蓝牙发现功能的库(JAR 文件)。
既然是一个库,那么里面的方法应该是一个顺序方法(启动蓝牙发现,等待一段时间,然后返回结果)。
我在下面编写了代码,但它不起作用。在 LogCat 中,我可以看到意图,但 BroadcastReceiver 无法捕获意图。
代码有问题吗?.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mSendButton = (Button) findViewById(R.id.button1);
mSendButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
doDiscovery();
}
});
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.e("device_name", device.getName());
Log.e("device_add", device.getAddress());
numberOfDevice++;
Found_Device = true;
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
if(numberOfDevice == 0){
Log.e("DISCOVERY", "No Device found");
}
Log.e("DISCOVERY", "Number of device :" + numberOfDevice);
Discovery_Finish = true;
}
}
};
public void doDiscovery(){
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
Discovery_Finish = false;
Found_Device = false;
long counter = 0;
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
mBluetoothAdapter.startDiscovery();
while((Found_Device == false) || (Discovery_Finish == false)){
counter++;
if (counter >= 1000000){
break;
}
}
// Add a code to check the number of device
unregisterReceiver(mReceiver);
mBluetoothAdapter.cancelDiscovery();
}
有没有办法在不使用BroadcastReceiver的情况下检查意图?
谢谢您的帮助。
我认为您错过了开始发现其他设备的过程。
执行此操作时,您将覆盖 IntentFilter:
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
你应该这样做:
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
filter.addAction(BluetoothDevice.ACTION_FOUND);