2012-08-02 77 views
0

我試圖使用ModBus協議連接到PLC。我打電話的ModBus從螺紋連接方法和我收到我的主線程上運行的通信異常... 我不知道它逃脫...Modbus協議轉義線程(Android,Jamod)

例外:



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

     } 

    } 

回答

0

在按一下按鈕,你叫comm.run()剛剛直接執行run()方法在UI線程的上下文。這是一個常見錯誤,您不應該直接在Thread實例上調用run()。使用comm.start()在工作線程的上下文中執行Modbus代碼。

Here is the Javadoc