2011-02-01 5 views
1

다음 주 클래스 및 스레드 -TCP 클라이언트가 있습니다. 클라이언트는 루프에서 실행되고 메시지를 수신하여 기본 클래스로 전달합니다. 메인 클래스에서는 메시지를 구문 분석하고받은 메시지의 이름과 값을 기반으로 다른 이미지를 표시하려고합니다. 예는 : shiftDirection & 값 : 이름 shiftDirection1 1Android : 둘 이상의 이미지를 표시 할 수 없습니다.

을하지만 단지 이미지가 먼저 수신 된 메시지에 대응하며, 나머지 수신 된 메시지에 대응하는 화상을 표시 할 수없는 표시 할 수있다.

아래 코드를 살펴보고 실수/문제 및 다른 방법을 제안하십시오.

시간과 노력에 감사드립니다.

마두

메인 클래스 :

public class TCPListen extends Activity implements TCPListener { 
    private TextView mTitle; 
    public String recData[] = new String[2]; 
    String PresentGear = "0"; 

    /** Called when the activity is first created. */ 
    @Override 
     public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState);     

      TcpServiceHandler handler = new TcpServiceHandler(this,this); 
      Thread th = new Thread(handler); 
      th.start();  
     }   

     public String[] callCompleted(String source){ 
       //Log.d("TCP", "Std parser " + source); 
       //mTitle.setText(source); 
       //String data[] = new String[2]; 

       //if (source.matches("<MSG><N>.*</N><V>.*</V></MSG>")) {   
        Document doc = null; 
        try{ 
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
         DocumentBuilder db = dbf.newDocumentBuilder(); 
         doc = (Document) db.parse(new ByteArrayInputStream(source.getBytes())); 
         NodeList n = doc.getElementsByTagName("N"); 
         Node nd = n.item(0); 
         String msgName = nd.getFirstChild().getNodeValue(); 
         NodeList n1 = doc.getElementsByTagName("V"); 
         Node nd1 = n1.item(0); 
         String tmpVal = nd1.getFirstChild().getNodeValue(); 
         recData[0] = msgName; 
         recData[1] = tmpVal; 
         if (recData[0].equals("currGear")) PresentGear = recData[1]; 
         Log.d("TCP", "Inside Std parser " + recData[0] + " " + recData[1]); 
         actionOnData(recData[0], recData[1]); 
         } 
        catch(Exception e){ 
        e.printStackTrace(); 
       }     
       Log.d("TCP", "Just outside Std parser " + recData[0] + " " + recData[1]); 
       return recData; 
       //} else Log.d("TCP", "Message in wrong format " + source); 
       //mTitle.setText("Message in wrong format " + source); 
       //return data; 
      } 


     //Function to display driver messages/images based on individual messages 
     public void actionOnData(String name, String value) { 
      String tempName = name; 
      String tempVal = value; 
      setContentView(R.layout.image); 
      ImageView showImage = (ImageView) findViewById(R.id.imageView1); 
      //Log.d("TCP", "------------>" + tempName + " " + tempVal);    

      if (tempName.equals("shiftDirection") && tempVal.equals("1")) { 
       //setContentView(R.layout.image); 
       //TextView text_top = (TextView) findViewById(R.id.textView1); 
       //showImage = (ImageView) findViewById(R.id.imageView1);    
       //text_bottom.setText(Info[1]); 
       showImage.setImageResource(R.drawable.shift_up); 
       Log.d("TCP", "1------------>" + showImage); 
      } else if (tempName.equals("shiftDirection") && tempVal.equals("-1")) {     
       //setContentView(R.layout.image); 
       //TextView text_bottom = (TextView) findViewById(R.id.textView2); 
       //Resources res = getResources(); 
       //Drawable drawable = res.getDrawable(R.drawable.shift_down); 

       //showImage = (ImageView) findViewById(R.id.imageView1);    
       //text_bottom.setText(Info[1]); 
       showImage.setImageResource(R.drawable.shift_down);    
      } else if (tempName.equals("recomGear") && tempVal != null) { 
       Log.d("TCP", "3------------>" + tempName + " " + tempVal); 
       Integer msgValue = Integer.parseInt(recData[1]); 
       //Integer CurrentGear = (msgValue) - 1; 
       //Log.d("TCP","in DA Images. Current gear: " + CurrentGear); 
       //String Gear = Integer.toString(CurrentGear); 
       setContentView(R.layout.image); 
       TextView text_top = (TextView) findViewById(R.id.textView1); 
       TextView text_bottom = (TextView) findViewById(R.id.textView2); 
       showImage = (ImageView) findViewById(R.id.imageView1);   
       showImage.setImageResource(R.drawable.shift_up); 
       text_bottom.setText(PresentGear); 
       text_top.setText(tempVal); 
      } else if (tempName.equals("currGear") && tempVal != null) { 
       Log.d("TCP", "4------------>" + tempName + " " + tempVal); 
       PresentGear = tempVal;   
       //Log.d("TCP","in DA Images. Present gear1: " + PresentGear); 
       setContentView(R.layout.image); 
       TextView text_bottom = (TextView) findViewById(R.id.textView2); 
       text_bottom.setText(PresentGear);      
      } else if (tempName.equals("shiftDirection") && tempVal.equals("0")) { 
       Log.d("TCP", "5------------>" + tempName + " " + tempVal); 
       Log.d("TCP","in DA Images. Present gear: " + PresentGear); 
       setContentView(R.layout.image); 
       TextView text_bottom = (TextView) findViewById(R.id.textView2); 
       //TextView text_top = (TextView) findViewById(R.id.textView1); 
       //text_top.setText("Go on"); 
       text_bottom.setText(PresentGear);   
      }   
      } 
} 

전용 케이스가 표시되면 상기 제에 대응하는 화상. 프로그램 컨트롤은 두 번째 if 루프를 시작하지만 거기에 이미지를 표시하지 않습니다.

인터페이스 :

public interface TCPListener { 
    public String[] callCompleted(String msg); 
} 

스레드 (TCP 클라이언트) :

public class TcpServiceHandler implements Runnable { 
    TCPListener _listener;    
    private Activity _act; 
    public BufferedReader in; 
    public TcpServiceHandler(TCPListener listener, Activity act){  
     _listener = listener; 
     _act = act; 
    }   

    public synchronized void run() { 
     // TODO Auto-generated method stub   
     //if(socket==null){  
      try { 
       //InetAddress serverAddr = InetAddress.getByName("192.168.178.25"); 
       Socket socket = new Socket("192.168.62.23", 1200, true); 
     // 
       //while(true){ 
        try {       
         in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
         final int delay = 100; 
         final Timer _timer = new Timer(); 
         _timer.scheduleAtFixedRate(new TimerTask() {      
          public void run(){ 
           String str; 
           try { 
            str = in.readLine(); 
            _listener.callCompleted(str); 
           } catch (IOException e) { 
            // TODO Auto-generated catch block 
            e.printStackTrace(); 
           } 

          } 
         }, 0, delay); 
         //final String str = in.readLine(); 
         //this._act.runOnUiThread(new Runnable(){ 

         //public void run() { 
         // _listener.callCompleted(str); 
          // }         
         //});             
        } 
        catch(Exception e){ 
         e.printStackTrace(); 
        } 
       //} 
      } catch (UnknownHostException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
    }  
} 

답변

1

당신은 2 일 확인 수 있습니다

  1. 당신의 TcpServiceHandler 스레드의 Runnable을하지만,이 run()에 루프가 없습니다. 이 메소드 내에서 정의한 _timer는 작업이 끝나기 전에 작동하지 않을 수 있습니다.

  2. 백그라운드 스레드에서 UI를 변경하고 있습니까? 이것은 일반적으로 좋은 생각이 아닙니다.

  3. 백그라운드에서 작업을 실행하는 편리한 도구 인 Check AsyncTask을 확인하십시오.

+0

TcpServiceHandler 내의 타이머가 올바르게 작동하고 있습니다. 실제로 들어오는 모든 메시지는 기본 클래스에도 전달됩니다. 그러나 이미지가 표시되지 않습니다. 백그라운드 스레드에서 UI를 변경하지 않을 것 같습니다. 이전에 비동기 작업을 시도했지만 복잡한 작업이있었습니다. –

+1

업데이트가 타이머 스레드에서 실행 중입니다. AsyncTask는 백그라운드에서 일어나는 일과 메인 스레드에서 발생해야하는 UI 업데이트 사이에 일을 전달하도록 설계되었습니다. IMHO 이것은 정확히 당신이 필요로하는 것입니다. 당신은 자신의 Handler를 구현하거나 runOnUiThread()를 호출 할 수 있습니다. (주석 처리 된 코드에서 시도한 것이 겠지요.)하지만 다시 AsyncTask를 다시 구현하는 것입니다. – Michael

관련 문제