我正计划开发一个Android应用程序,通过TCP套接字与PC程序进行通信。该应用程序将有几个活动(布局),每个活动代表一个不同的物理设备,连接到PC。我想有一个TCP套接字连接到PC服务器时,应用程序第一次打开,然后在后台运行。当用户有设备的活动时,打开的TCP套接字应该不断地向主机发送设备状态的请求,然后用最新的数据更新UI。
我一直在研究运行后台任务的不同可能性,我不确定在这种情况下哪个选项最好。我的TCP操作系统应该继续在线程上运行吗?我理解服务只应该用于非阻塞操作,并且我不能保证网络事务将是即时的(特别是当网络连接丢失时)。
如果我要在线程中运行通信,那么最好的方法是通知UI新的数据已经到了。另外,当用户切换到不同的活动时,提醒线程开始请求有关不同设备的信息的最佳方法是什么?
发布于 2011-09-09 13:44:26
我们正在构建一个Android应用程序,它通过TCP套接字与硬件通信,监听设备上的各种事件,并通过用户的操作与其通信。与您将要做的类似,我们的应用程序也有几个活动,它们根据活动的上下文获取不同的数据。对于该应用程序,我们采取了以下方法:
onStart向服务器发送请求类型开关。由于以前注册的处理程序处理特定上下文(通过请求类型),如果响应与新请求类型不匹配,它们将忽略响应。请求和响应处理程序都实现为AsyncTask,下面是ResponseHandler的存根,以便您更好地理解我所写的内容:
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;
}
}https://stackoverflow.com/questions/7361367
复制相似问题