目前我正在尝试将Java编码转换为Android studio。 这是原始代码
public static void main(String[] args)
{
ModbusClient modbusClient = new ModbusClient("192.168.1.106",502);
try
{
modbusClient.Connect();
modbusClient.WriteSingleCoil(0, true);
modbusClient.WriteSingleRegister(0, 1234);
modbusClient.ConvertFloatToTwoRegisters((float) 123.56));
}
catch (Exception e)
{
}
}
这是Android Studio中已编辑的版本:
public class medusaTest extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mb);
Button b = (Button)this.findViewById(R.id.btn1);
b.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
ModbusClient modbusClient = new ModbusClient("192.168.1.106",502);
try
{
modbusClient.Connect();
modbusClient.WriteSingleCoil(0, true);
modbusClient.WriteSingleRegister(0, 1234);
modbusClient.WriteMultipleRegisters(11, ModbusClient.ConvertFloatToTwoRegisters((float) 123.56));
//System.out.println(modbusClient.ReadCoils(0, 1)[0]);
//System.out.println(modbusClient.ReadHoldingRegisters(0, 1)[0]);
//System.out.println(ModbusClient.ConvertRegistersToFloat(modbusClient.ReadHoldingRegisters(11, 2)));
}
catch (Exception e)
{
}
}
});
}
}
问题是,每当我试图在Android上运行它时,它就会一直停止应用程序。请给我建议并帮助我在Android中运行此代码。谢谢
答案 0 :(得分:1)
确保将互联网权限添加到manifest.xml
文件中。
<uses-permission android:name="android.permission.INTERNET" />
答案 1 :(得分:0)
我设法找到了我的问题的答案。解决方案
在公共类
中的Setcontentview(R.Layout.main_activity)之后添加代码代码:
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
我的问题已经解决了。感谢