KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I am working on an Android application that requires a TCP connection to a TCP server(Written in Node.js) My Android TCP client is working an can send messages back and forth. My spesific questions is: What is the best way to handle a TCP connection to a server in Android ? How to maintain the connection(close the connection properly on onDestroy() etc) ? Is there any bether way then using an AsyncTask(Except a normal Thread class, which is not allowed in Android 4.0) I have my socket connection in an AsyncTask like this: @Override protected Void doInBackground(Void... params) { try { Log.d("TCP_MESSAGE", "Connecting..."); socket = new Socket(MY_LOCAL_IP, 8080); dataOutput = new DataOutputStream(socket.getOutputStream()); inputstream = new InputStreamReader(socket.getInputStream()); input = new BufferedReader(inputstream); while (!canceled) { String message = input.readLine(); handleMessage(message); } } catch (Exception e) { e.printStackTrace(); } } return null; } The reason i have the connection in an AsyncTask is because i am using android 4.0 and are not allowed to have network code in a regular Thread.
Tags (comma-separated)
Save Edits
Cancel