0

我正在尝试使用 ModBus 协议连接到 PLC。我正在从线程调用 ModBus 连接方法,并且我正在主线程上运行通信时遇到异常......我想知道它在哪里逃脱......

例外:



    08-02 10:48:44.461: W/System.err(4395): android.os.NetworkOnMainThreadException
    08-02 10:48:44.471: W/System.err(4395):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
    08-02 10:48:44.471: W/System.err(4395):     at 

代码:




    package com.kikudjiro.android.echo;

    import net.wimpi.modbus.facade.ModbusTCPMaster;
    import android.app.Activity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;

    public class settings extends Activity implements Runnable {

        Button connect_b, disconnect_b;
        Thread comm = new Thread(this);

        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.settings);
            addListenerOnButton();
        }

        public void addListenerOnButton() {

            connect_b = (Button) findViewById(R.id.button1);
            disconnect_b = (Button) findViewById(R.id.button2);
            connect_b.setOnClickListener(new OnClickListener() {
                public void onClick(View arg0) {
                    comm.run();
                }

            });

            disconnect_b.setOnClickListener(new OnClickListener() {

                public void onClick(View arg0) {
                    comm.interrupt();
                }

            });
        }

        // @Override
        public void run() {

            try {
                ModbusTCPMaster MB = new ModbusTCPMaster("192.168.107.29", 502);
                //while (!comm.interrupted()) {
                    Log.i("!!!!!!!", "try!");
                    MB.connect();
                    MB.writeCoil(1, 1, true);
                    MB.disconnect();
                //}
            }

            catch (Exception ex) {
                ex.printStackTrace();
                Log.i("hhh", "exceptionas!!!");
            } finally {
                Log.i("!!!!!!!", "finally!");
            }

        }

    }

4

1 回答 1

0

单击按钮时,您调用comm.run()的只是run()直接在 UI 线程的上下文中执行该方法。这是一个常见错误,您永远不应该run()直接调用Thread实例。用于comm.start()在工作线程的上下文中执行 Modbus 代码。

这是Javadoc

于 2012-08-02T08:48:10.333 回答