Android的TCP连接的最佳实践 [英] Android TCP connection best practice

查看:336
本文介绍了Android的TCP连接的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的一个Android应用程序,需要一个TCP连接到TCP服务器(写在Node.js的)

I am working on an Android application that requires a TCP connection to a TCP server(Written in Node.js)

我的Andr​​oid TCP客户端工作的可以发送邮件来回。

My Android TCP client is working an can send messages back and forth.

我的提问spesific是:

My spesific questions is:


  1. 什么是处理在Android的TCP连接到服务器的最佳方式?

  2. 如何保持连接(正确关闭连接上的onDestroy()等)?

  3. 有什么办法bether然后使用AsyncTask的(除正常的Thread类,这是不是在Android 4.0的允许)

我有一个这样在AsyncTask的我的socket连接:

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;
}

我之所以在AsyncTask的连接是因为我使用的Andr​​oid 4.0,并且不允许有网络code在常规的螺纹。

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.

推荐答案

一个服务应该拥有的连接。如果你需要保留,而您的应用程序没有运行的连接,那么你应该让一个前台服务。如果你不让它前台服务,请确保绑定到该服务的活动,以保持它活着。

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.

不要忘了,服务也运行在主(UI)线程,所以你仍然需要一个单独的线程来处理通信。

Don't forget that the service also runs on the main (UI) thread so you still need a separate thread to handle the communication.

如果你只有一个活动,只是想处理由于配置的变化,那么你就可以处理配置改变自己,保持一个非UI片段拥有的连接,或通过使用onRetainNonConfigurationInstance自己的连接重新启动() / getLastNonConfigurationInstance()(当然,这是有利于利用碎片pcated德$ p $)。

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

这篇关于Android的TCP连接的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆