我在 Android 应用程序中使用 modbus4j。在我用java测试它之前,它工作正常。但在 Android 中,master.init() 有问题,它不起作用。在清单中,我添加了 Internet 和访问网络状态的权限。我有一个或多或少这样的代码:
// Perform action on click
// Read IP from layout***
EditText edittext_IP = (EditText) findViewById(R.id.editText1);
TextView MWReaded = (TextView) findViewById(R.id.textView4);
// **********************
//
String slaveIP;
slaveIP = edittext_IP.getText().toString();
ModbusFactory factory = new ModbusFactory();
IpParameters params = new IpParameters();
params.setHost(slaveIP);
params.setPort(502);
params.setEncapsulated(false);
ModbusMaster master = factory.createTcpMaster(params, true);
master.setTimeout(500);
master.setRetries(2);
try {
master.init();
} catch (ModbusInitException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplication(),
"Error: " + e.getMessage(), 10).show();
}
ModbusLocator locator = new ModbusLocator(1,
RegisterRange.HOLDING_REGISTER, 0,
DataType.TWO_BYTE_INT_UNSIGNED);
Object xx = null;
try {
xx = master.getValue(locator);
} catch (ModbusTransportException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ErrorResponseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int Register = 0;
if (xx != null){
Register = Integer.parseInt(xx.toString());
} else{
Register = 6969;
}
MWReaded.setText(String.valueOf(Register));
TextView txttest_n = (TextView) findViewById(R.id.textView5);
txttest_n.setText("n=" + n);
n = n + 1;
}
});
但是主人永远不会被初始化。我可以看到一个例外。“android.os.NetworkOnMainThreadException”
你知道我该如何解决这个问题吗?