我有一个通过蓝牙连接到RaspberryPi的应用程序,并在收到一些数据时将相同的数据循环到它.
我有一些连接问题,所以需要这个解决方法将我的Android手机连接到RaspberryPi:IOException:读取失败,套接字可能关闭 - Android 4.3上的蓝牙
由于某种原因,Android手机正在接收自己的输出.字符串"Hello Raspberry.这是我,AndroidPhone"以永无止境的循环发送到输出.传入的数据(来自RaspberryPi)也在一个永无止境的循环中读取.
但不知何故,我不仅收到RaspberryPi的数据,还收到通过智能手机发送的字符串.这是我的代码:
public class MainActivity extends AppCompatActivity {
private BluetoothAdapter bluetoothAdapter;
UUID SERIAL_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
@Override
protected void onCreate(Bundle savedInstanceState) {
// (...)
// Only GUI-stuff until this point
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice raspberryPi = bluetoothAdapter.getRemoteDevice("B8:27:EB:56:DC:B2");
BluetoothSocket btSocket;
try {
btSocket = raspberryPi.createRfcommSocketToServiceRecord(SERIAL_UUID);
btSocket.connect();
} catch (IOException e) {
Log.e("BTError", e.getMessage());
// Workaround, found on: https://stackoverflow.com/questions/18657427/ioexception-read-failed-socket-might-closed-bluetooth-on-android-4-3
try {
Log.e("BTError", "Trying fallback...");
btSocket = (BluetoothSocket) raspberryPi.getClass().getMethod("createRfcommSocket", new Class[]{int.class}).invoke(raspberryPi, 1);
btSocket.connect();
(new Thread(new …Run Code Online (Sandbox Code Playgroud) 我有一个对象,它有几个数组作为字段.它的类大致如下所示:
public class Helper {
InsuranceInvoices[] insuranceInvoices;
InsuranceCollectiveInvoices[] insuranceCollectiveInvoices
BankInvoices[] bankInvoices;
BankCollectiveInvoices[] bankCollectiveInvoices;
}
Run Code Online (Sandbox Code Playgroud)
所有发票类型都有一个共同标记界面发票.
我需要获取所有发票才能调用其他方法.
Helper helperObject = new Helper();
// ...
for (InsuranceInvoices invoice : helperObject.getInsuranceInvoices()) {
Integer customerId = invoice.getCustomerId();
// ...
}
for (BankInvoices invoice : helperObject.getBankInvoices()) {
Integer customerId = invoice.getCustomerId();
// ...
}
// repeat with all array fields
Run Code Online (Sandbox Code Playgroud)
问题是所有发票只有标记接口.方法getCustomerID()不是由相互接口或类定义的.这是一种由于给定的规范而无法改变的行为.
for-each-loops中的代码重复是让我烦恼的事情.我必须对四个不同阵列中的所有发票对象执行完全相同的操作.因此,四个for-each-loops不必要地膨胀代码.
有没有办法可以编写一般(私有)方法?一个想法是:
private void generalMethod(Invoice[] invoiceArray){
// ...
}
Run Code Online (Sandbox Code Playgroud)
但这需要四个instanceof检查,因为类Invoice不知道方法getCusomterId().因此,我什么也得不到; 该方法仍然包含重复.
我很感谢每一个可能的解决方案来概括这个问题!