Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android TCP connection best practice

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:

  1. What is the best way to handle a TCP connection to a server in Android ?
  2. How to maintain the connection(close the connection properly on onDestroy() etc) ?
  3. 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.

like image 402
Emil Avatar asked Oct 19 '12 13:10

Emil


1 Answers

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).

like image 194
Tobias Ritzau Avatar answered Oct 05 '22 08:10

Tobias Ritzau