Modbus protocol escapes the thread (Android,Jamod)

倾然丶 夕夏残阳落幕 提交于 2019-12-12 06:24:46

问题


I'm trying to connect to PLC using ModBus protocol. I'm calling ModBus connect method from thread and I'm getting exception that I'm running communications on the main thread... I wonder where it escapes...

Exception:



    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 

Code:




    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!");
            }

        }

    }


回答1:


On button click, you call comm.run() which just executes the run() method directly in the context of the UI thread. This is a common error, you should never call run() directly on a Thread instance. Use comm.start() to execute the Modbus code in the context of your worker thread.

Here is the Javadoc



来源:https://stackoverflow.com/questions/11773864/modbus-protocol-escapes-the-thread-android-jamod

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!