我目前正在开发一个小应用程序,以开始使用蓝牙Android API提供的服务。
编辑->答案:
看起来问题是由于特定的Nexus 5设备引起的。似乎它们的蓝牙接收器不工作良好。下面的解决方案应该适用于其他设备
备注:
我已经阅读了这里的文档:http://developer.android.com/guide/topics/connectivity/bluetooth.html,以及此教程http://www.londatiga.net/it/programming/android/how-to-programmatically-scan-or-discover-android-bluetooth-device/的源代码,位于/lorensiuswlt/AndroBluetooth下。
我几乎完成了我感兴趣的所有功能(例如检查适配器是否存在、启用/禁用蓝牙、查询配对设备、将适配器设置为可发现)。
问题:
实际上,在我启动.onDiscovery()方法时没有找到任何设备,即使在我的Nexus 5上从“设置/蓝牙”中找到设备。
以下是我的处理方式:
public class MainActivity extends AppCompatActivity {
private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
...
protected void onCreate(Bundle savedInstanceState) {
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
}
就我所尝试的,过滤器运行良好,即 ACTION_STATE_CHANGED(在蓝牙启用时)和两个 ACTION_DISCOVERY_***。
接下来成功调用了以下方法:
public void onDiscovery(View view)
{
mBluetoothAdapter.startDiscovery();
}
然后我有我的蓝牙接收器:
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
if (state == BluetoothAdapter.STATE_ON) {
showToast("ACTION_STATE_CHANGED: STATE_ON");
}
}
else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
mDeviceList = new ArrayList<>();
showToast("ACTION_DISCOVERY_STARTED");
mProgressDlg.show();
}
else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action) && !bluetoothSwitchedOFF) {
mProgressDlg.dismiss();
showToast("ACTION_DISCOVERY_FINISHED");
Intent newIntent = new Intent(MainActivity.this, DeviceListActivity.class);
newIntent.putParcelableArrayListExtra("device.list", mDeviceList);
startActivity(newIntent);
}
else if (BluetoothDevice.ACTION_FOUND.equals(action)) {// When discovery finds a device
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mDeviceList.add(device);
showToast("Device found = " + device.getName());
}
}
};
我没有任何问题从logcat中出来,并且在我进行的测试期间没有注意到任何问题。唯一的问题是,在扫描结束时,即使附近有很多可发现设备,没有发现任何设备。
为了避免淹没主题,我尝试不放太多代码。如果需要,请问我。
感谢您阅读我的内容,并提前感谢您的回答。