Android应用TCP工人 [英] Android app TCP worker

查看:135
本文介绍了Android应用TCP工人的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我规划出一个Android应用程序,通过TCP套接字一个PC程序进行通信。该应用程序将有几个活动(布局),每个重present连接到PC机不同的物理设备。我想有一个连接到PC服务器,当应用程序首次打开,然后在后台运行的TCP套接字。当用户对设备-A打开TCP套接字应继续将请求发送到主机设备-A状态,然后用最新的数据更新UI活动。

I am planning out an Android app that communicates with a PC program via a TCP Socket. The app will have several Activities(layout) each of which represent a different physical device which is connected to the PC. I would like to have a TCP socket that connects to the PC server when the app first opens and then runs in the background. When the user has the Activity for Device-A open the TCP socket should continually send requests to the host for Device-A status and then update the UI with the most recent data.

我一直在寻找的在后台运行的不同的可能性,我不知道哪个选项最好是在这种情况下。如果我的TCP OPS是连续在一个线程中运行?据我所知,维修服务只能用于非阻挡的操作,我不能保证网络交易将瞬间(特别是如果连接到网络的丢失)。

I have been looking at the different possibilities for running background tasks and I am not sure which option is best in this case. Should my TCP ops be continuously running on a Thread? I understand that a Service should only be used for non-blocking operations and I cannot guarantee that network transactions will be instantaneously (especially if connection to the network is lost).

如果我是运行在一个线程什么是提醒新的数据已经到达了UI的最佳方式沟通。此外,当用户切换到一个不同的活动是什么,以提醒线程开始请求关于一个不同的设备的信息的最佳方式

If I were to run the communication in a thread what is the best way to alert the UI that new data has arrived. Also, when the user switches to a different activity what is the best way to alert the thread to start requesting information about a different device?

推荐答案

我们正在构建一个通过TCP套接字与硬件进行通信的设备听各种活动,以及通过用户的操作与它通信的Andr​​oid应用程序。类似于您将要做些什么,我们的应用程序也已经是基于活动的背景下获得不同的数据的几个活动。对于应用程序,我们已经做了以下的方法:

We are building an Android app that is communicating with a hardware via TCP socket listening to various events from the device as well as communicating with it via user's actions. Similar to what you are about to do, our app has also several Activities that are getting different data based on the context of the activity. For the app, we have done the following approach:


  • 创建一个响应和请求处理程序,负责打开插座输出和输入流。

  • 我们在自己的线程跑了这两个。请求处理程序正在从阻塞队列包含请求的请求

  • 每个请求等同于它的类型,请求ID,时间戳和处理程序。

    • 的类型标识请求的情况下(在你的情况下,设备类型)

    • 处理器是使用 Android的处理器是负责处理与特定的ID和类型要求。你的情况,你将有DeviceAHandler,DeviceBHandler等,将要使用特定的标识和类型相关联。通过这种方法,您可以处理程序处理特定UI更新特定设备

    • Create a Response and Request Handler that is responsible for opening the socket output and inputstream.
    • We ran these two on its own Thread. The Request Handler is taking the request from a blocking queue that contains the request
    • Each Request is identified with its type, request id, timestamp and a Handler.
      • The type identifies the context of the request (in your case, the device type)
      • A Handler is using Android Handler that is responsible for handling a request with specific id and type. In your case you will have DeviceAHandler, DeviceBHandler etc, that you will associate with specific id and type. With this approach, your Handler can handle a specific UI update for specific device

      请求和响应处理程序实现为AsyncTask的,下面是对ResponseHandler所存根,让你可以更好地理解了我写的:

      Both Request and Response Handler are implemented as AsyncTask, below are the stub for the ResponseHandler so that you could understand better what I wrote :

      
      public class ResponseHandler extends AsyncTask {
          boolean isConnectionClosed = false;
      
          @Override
          protected Integer doInBackground(Void... params) {
              int errorCode = 0;
      
              try {
                  // while not connection is not close
                  while(!isConnectionClosed){
                      // blocking call from the device/server
                      String responseData = getResponse();
      
                      // once you get the data, you publish the progress
                      // this would be executed in the UI Thread
                      publishProgress(responseData);
                  }
              } catch(Exception e) {
                  // error handling code that assigns appropriate error code
              }
      
              return errorCode;
      
          }
      
          @Override
          protected void onPostExecute(Integer errorCode) {
              // handle error on UI Thread
          }
      
          @Override
          protected void onProgressUpdate(String... values) {
              super.onProgressUpdate(values);
              String responseData = values[0];
      
              // the response contains the requestId that we need to extract
              int requestId = extractId(responseData);
      
              // next use the requestId to get the appropriate handler
              Handler uiHandler = getUIHandler(requestId);
      
              // send the message with data, note that this is just the illustration
              // your data not necessary be jut String
              Message message = uiHandler.obtainMessage();
              message.obj = responseData;
              uiHandler.sendMessage(message);
          }
      
          /***
           * Stub code for illustration only
           * Get the handler from the Map of requestId map to a Handler that you register from the UI
           * @param requestId Request id that is mapped to a particular handler
           * @return
           */
          private Handler getUIHandler(int requestId) {
              return null;
          }
      
          /***
           * Stub code for illustration only, parse the response and get the request Id
           * @param responseId
           * @return
           */
          private int extractId(String responseId) {
              return 0;
          }
      
          /***
           * Stub code for illustration only
           * Call the server to get the TCP data. This is a blocking socket call that wait
           * for the server response
           * @return
           */
          private String getResponse() {
              return null;
          }
      }
      

      这篇关于Android应用TCP工人的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆