Monday, 26 August 2013

Android sockets: receiving data in real-time

Android sockets: receiving data in real-time

I have another device & application transmitting data in real-time (every
few ms) and on my receiving device, I want to:
1) read/receive this data, and 2) use it to update a UI element (a dynamic
graph in this case)
The data sender uses a socket in a background service, using AsyncTasks
every few ms to send data. To initialize, it does the following:
echoSocket = new Socket(HOST, PORT);
out = new PrintWriter(echoSocket.getOutputStream(), true);
And to periodically send data it does:
static class sendDataTask extends AsyncTask<Float, Void, Void> {
@Override
protected Void doInBackground(Float... params) {
try {
JSONObject j = new JSONObject();
j.put("x", params[0]);
j.put("y", params[1]);
j.put("z", params[2]);
String jString = j.toString();
out.println(jString);
} catch (Exception e) {
Log.e("sendDataTask", e.toString());
}
return null;
}
}
How should I go about receiving this data in my application? Should I also
use a background service with AsyncTasks that try to read from the socket
every few ms? How about communicating with the UI thread?

No comments:

Post a Comment