Alex Rivera | Logout

Android TCP connection best practice

Asked 2012-10-19T13:15:55.763
11

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.

Edit
Report

1 Answer

2

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

answered 2012-10-19T13:37:16.103

Your Answer