所以我创建了这样的东西:
final BluetoothSocket[] clientSocket = new BluetoothSocket[1];
devicesSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
try {
BluetoothDevice remoteDevice = bluetoothAdapter.getRemoteDevice(devices.get(i).getAddress());
Method m = remoteDevice.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
clientSocket[0] = (BluetoothSocket) m.invoke(remoteDevice, 1);
Log.i("DATA_FROM_REMOTE_DEVICE", "" + clientSocket[0].getInputStream().read());
} catch (Exception e){
Log.i("REMOTE_DEVICE", "No such a method", e);
}
Toast.makeText(getApplicationContext(), "Selected to: " + devices.get(i).getName(), Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected (AdapterView<?> adapterView){
}
});
问题是如果我在“try catch”块之间添加:
clientSocket[0].connect();
一切正常,但是当我运行app并将数据加载到微调器时,它会自动开始连接到第一个找到的设备,这不是我想要的。我宁愿选择选择我想要连接的设备。所以我决定将该行移动到其他监听器,但我不确定我应该使用哪个,因为第一个选项是“onClick”但它不适用于Spinner所以我尝试使用“onTouch”但是也不能像我一样工作我想,请你告诉我应该如何实施它?