【发布时间】:2017-06-07 18:15:36
【问题描述】:
我正在构建一个通过蓝牙连接到 Arduino 板的 android 应用程序。我设法连接并发送数据。在第一个活动中,我列出了所有配对设备和可用设备,当我单击其中一个设备时,如果它可用,它将连接到板,但如果它不可用(单击配对设备,但这个是不在附近或蓝牙已停用)应用程序显示一个对话框,指示设备正在尝试连接并且无法关闭。当手机无法连接到所选设备时,是否会触发任何事件?
我认为这可以通过设置计时器来关闭对话框来完成,在这种情况下,我该如何停止正在进行的连接尝试?我一直在寻找几天,我发现的唯一解决方案与断开连接和状态更改事件有关。提前致谢。
这是我的代码
public void setOnDiscoveryListener(final OnDiscoveryListener listener){
oldReceiver = receiver;
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
switch (action){
case BluetoothAdapter.ACTION_DISCOVERY_STARTED:
listener.onStartDiscovery();
break;
case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:
listener.onStopDiscovery();
break;
case BluetoothDevice.ACTION_FOUND:
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
listener.onDeviceDiscovery(device);
break;
case BluetoothDevice.ACTION_ACL_CONNECTED:
listener.onDeviceConnected();
break;
case BluetoothDevice.ACTION_ACL_DISCONNECTED:
listener.onDeviceDisconnected();
break;
}
}
};
}
我使用一个接口来初始化广播接收器。
bluetoothManager.setOnDiscoveryListener(new BluetoothManager.OnDiscoveryListener() {
@Override
public void onStartDiscovery() { }
@Override
public void onStopDiscovery() {
progressBar.hide();
refreshLayout.setEnabled(true);
bluetoothManager.updateOnDiscoveryListener(discoveryListener);
if(noAvailableDevices)
noAvailableDevicesText.setVisibility(View.VISIBLE);
}
@Override
public void onDeviceDiscovery(BluetoothDevice bluetoothDevice) {
noAvailableDevices = false;
availableDevicesAdapter.addDevice(new Device(bluetoothDevice.getName(), bluetoothDevice.getAddress()));
}
@Override
public void onDeviceConnected() {
progressDialog.dismiss();
Intent intent = new Intent(activity, MenuActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
@Override
public void onDeviceDisconnected() { }
});
最后,我使用了这些过滤器。
bluetoothManager.setDiscoveryFilters(activity, new String[]{
BluetoothAdapter.ACTION_DISCOVERY_STARTED,
BluetoothAdapter.ACTION_DISCOVERY_FINISHED,
BluetoothDevice.ACTION_FOUND,
BluetoothDevice.ACTION_ACL_CONNECTED,
BluetoothDevice.ACTION_ACL_DISCONNECTED});
这是列表项的 OnClick 事件的代码。
private View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View view) {
String deviceName = ((TextView) view.findViewById(R.id.device_name)).getText().toString();
String deviceAddress = ((TextView) view.findViewById(R.id.device_address)).getText().toString();
progressDialog = ProgressDialog
.show(activity, null, getResources().getString(R.string.connecting) + " " + deviceName, true);
Intent intent = new Intent(activity, BluetoothService.class);
intent.putExtra(Constants.MAC_KEY, deviceAddress);
activity.startService(intent);
}
};
【问题讨论】:
-
请在此处发布您的代码 - 您正在调用的 API 以初始化..connect 等
-
我已经发布了我的代码。谢谢。
-
使用调试器/日志你看到
BluetoothAdapter.ACTION_DISCOVERY_STARTED:被命中了吗? -
我假设您有足够的清单权限:`“android.permission.BLUETOOTH”`
-
同时发布您点击配对设备并尝试连接的代码