Android手机中的TCP客户端:连续运行,根据从服务器收到的消息显示图像

时间:2011-01-25 23:07:36

标签: android image tcpclient

我有一个在Android手机上运行的TCP客户端。它连接并从Windows应用程序接收数据。收到邮件后,我会解析它,然后尝试显示图像。我必须继续检查来自这个Windows应用程序的新消息。

客户端线程一直在运行。收到消息后,我将其传递给主活动,解析它但我无法显示图像。我想让客户端每100毫秒检查一次新消息。目前,当线程继续运行时,LogCat会被淹没,我无法真正看到LogCat的内容。

基本上我想运行客户端,每100毫秒检查一次新消息,当有新消息时,将其传递给主活动,解析它并显示图像。如有必要,请仔细阅读以下代码并提出任何更正建议或更好的方法。

客户端代码如下。

主要活动:

public class TCPListen extends Activity implements TCPListener {
 private TextView mTitle;
 public String data[] = new String[2];

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

       // Set up the window layout
          requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
          setContentView(R.layout.main);
          getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);

          // Set up the custom title
          mTitle = (TextView) findViewById(R.id.title_left_text);
          mTitle.setText(R.string.app_name);
          mTitle = (TextView) findViewById(R.id.title_right_text);

          //TcpServiceHandler handler=new TcpServiceHandler(this);
          //handler.execute("192.168.62.23");

          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();
                 data[0] = msgName;
                 data[1] = tmpVal;
                 Log.d("TCP", "Inside Std parser " + data[0] + " " + data[1]);
                 actionOnData(data[0], data[1]);
                }
              catch(Exception e){
              e.printStackTrace();
          }
          Log.d("TCP", "Just outside Std parser " + data[0] + " " + data[1]);
          return data;
          //} 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;
       //while (true) {
        if(tempName.equals("shiftDirection") && tempVal.equals("1")) {
         Log.d("TCP","in actionOnData " + data[0] + " " + data[1]);
         mTitle.setText("Change to next higher gear");
               Intent myIntent = new Intent();
               myIntent.setClassName("com.example.android.TCPListen", "com.example.android.TCPListen.Images");
               //myIntent.putExtra("Change gear", "Shift to next gear!"); // key/value pair, where key needs current package prefix.
               startActivity(myIntent);
               try {
              wait(3000);
              } catch(InterruptedException e) {
              System.out.println("InterruptedException caught");
              }
           } else if(tempName.equals("vehicleSpeed") && tempVal.equals("120")) {
         Log.d("TCP","in actionOnData " + data[0] + " " + data[1]);
         mTitle.setText("Drive like a man");
               //Intent myIntent = new Intent();
               //myIntent.setClassName("com.example.android.TCPListen", "com.example.android.TCPListen.Images");
               ////myIntent.putExtra("Change gear", "Shift to next gear!"); // key/value pair, where key needs current package prefix.
               //startActivity(myIntent);
           } else Log.d("TCP", "Just show an image");

       //}

      }
}

接口:

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

主题:

public class TcpServiceHandler implements Runnable {
     TCPListener _listener;
     private Activity _act;
     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.2.103", 1200, true);
         //
                 while(true){
                  try {
                         BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                         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 个答案:

答案 0 :(得分:1)

由于您询问了有关更好方法的建议,您可能会考虑将服务作为TCP侦听器而不是活动,并且当检测到消息时,它可以打开显示所需图像的活动。它更复杂,但如果我理解正确,它似乎更符合传统上使用的活动和服务。我想这取决于消息之间的等待时间和用户等待时发生的事情。