开发者

TCP client in Android phone: run continuously, display image based on message received from server

I have a TCP client running in Android phone. It connects and receives data from a windows application. Once I receive a message, I parse it and I try to display an image. I have to keep checking for new messages from this windows app.

The client thread keeps running. When a message is received, I pass it to the main activity, parse it but I am not able to display the image. I want to make the client check for new message every 100 ms. At the moment, the LogCat gets flooded as the thread keeps running and I am not able to really see the contents of LogCat.

Basically I want to run the client, keep checking for new messages every 100 ms, when a new message is there, pass it to the main activity, parse it and display an image. Please go through the code below and suggest any corrections or a better approach if necessary.

The client code is below.

Main activity:

public class TCPListen extends Activity implements TCPLi开发者_JS百科stener {
 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");

       //}

      }
}

Interface:

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

Thread:

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();
             }
     }
 }


Since you asked for suggestions for better approaches, you might consider having a Service be the TCP listener instead of an Activity and when a message is detected it could open an Activity that shows the image you want. It's more complicated, but it seems more in keeping with what Activities and Services are traditionally used for, if I'm understanding correctly. I guess it depends on things like how long the wait is between messages and what's going on while the user is waiting.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜