Reputation: 6845
Android noob here. I learn the best by seeing the source code of a functional example, but I have been unable to find a simple-but-complete example of using a socket in its own thread.
I have an Android service that needs to communicate with the Internet. I want to open a TCP socket that connects to a server on the Internet. The service needs to send data to the Internet, and data coming back from the net will need to go to the service. Since the service is doing other things as well, the socket connection needs to live in its own thread.
Any idea where I could find an example of a socket in a thread with communication to/from the socket?
Thanks
Upvotes: 9
Views: 30329
Reputation: 4751
You simply need to create an async task that communicates in the background and then updates the UI thread as needed. Here is the background thread to get information from a socket and update a text view with the number of bytes it receivers
public class InternetTask extends AsyncTask<Void, Integer, Void> {
private WeakReference<TextView> mUpdateView;
public LoginTask(TextView view) {
this.mUpdateView = new WeakReference<TextView>(view);
}
@Override
protected Void doInBackground() {
try {
Socket socket = new Socket("127.0.0.1", 80);
InputStream is = socket.getInputStream();
byte[] buffer = new byte[25];
int read = is.read(buffer);
while(read != -1){
publishProgress(read);
read = is.read(buffer);
}
is.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onProgressUpdate(Integer... values) {
if(mUpdateView.get() != null && values.length > 0){
mUpdateView.get().setText(values[0].toString());
}
}
}
And here is how you would kick that thread off
public class TestTab extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.someLayout);
TextView textView = (TextView)findViewById(R.id.someid);
InternetTask task = new InternetTask(textView);
task.execute();
}
}
Upvotes: 15
Reputation: 41858
Here is a long blog about this subject, where both the server and client parts are showing, with the socket communication going over a separate thread.
One thing to be aware of is that if you are passing int
s you may run into a byte-order problem, so, just do some testing and I would suggest you ensure that the server sends in the format that the Android needs, in case you have servers on more than one OS.
For a simple way, on the Android to find the byte order you can use this: http://developer.android.com/reference/java/nio/ByteOrder.html
According to this article, byte order may be swapped for optimization: http://en.wikipedia.org/wiki/Dalvik_(software)
Upvotes: 8