Reputation: 146
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:
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.
Upvotes: 11
Views: 12661
Reputation: 25873
What is the best way to handle a TCP connection to a server in Android?
This heavily depends on the complexity of your app, and what you want to do with it. There are no specifics for Android networking.
How to maintain the connection(close the connection properly on onDestroy() etc) ?
Open the socket whenever you fell to and keep it as a class field. Close it when onDestroy()
is called. Make sure you check if it's not null
first.
Is there any bether way then using an AsyncTask(Except a normal Thread class, which is not allowed in Android 4.0)
You can use normal Java threads in Android 4.0 (API14). You might have a confusion: what is not allowed in Android is having network code in the main thread (UIThread).
Upvotes: 2
Reputation: 3327
A Service should own the connection. If you need to keep the connection while your app is not running, then you should make it a foreground service. If you don't make it a foreground service, make sure to bind to the service from your activities to keep it alive.
Don't forget that the service also runs on the main (UI) thread so you still need a separate thread to handle the communication.
If you only have one activity and just want to handle restarts due to configuration changes, then you can handle the configuration changes yourself, keep the connection owned by a non-ui fragment, or pass the connection to yourself using onRetainNonConfigurationInstance()/getLastNonConfigurationInstance() (however that is deprecated in favor of using fragments).
Upvotes: 6