Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/192.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 在后台线程中发送和接收文本数据_Android_Multithreading_Android Handler - Fatal编程技术网

Android 在后台线程中发送和接收文本数据

Android 在后台线程中发送和接收文本数据,android,multithreading,android-handler,Android,Multithreading,Android Handler,我是为Android开发的新手。我的应用程序是TCP服务器之外的客户端。我需要用套接字在后台线程中将文本数据从EditText发送到服务器。回答我需要添加到TextView的服务器。我看到很多例子,但没有看到我能理解的例子。所以我需要一个简单的例子,尽可能地为我特别。对不起我的英语。 AsyncTask仅用于一次性使用。我只需要一根线。据我所知,我需要:线程(可运行)、处理程序、消息、循环器。。但我不明白如何为我使用这些课程 ublic class ServerWork extends Thre

我是为Android开发的新手。我的应用程序是TCP服务器之外的客户端。我需要用套接字在后台线程中将文本数据从EditText发送到服务器。回答我需要添加到TextView的服务器。我看到很多例子,但没有看到我能理解的例子。所以我需要一个简单的例子,尽可能地为我特别。对不起我的英语。 AsyncTask仅用于一次性使用。我只需要一根线。据我所知,我需要:线程(可运行)、处理程序、消息、循环器。。但我不明白如何为我使用这些课程

ublic class ServerWork extends Thread{

public static final Character PREFIX = ###;
public static final Character SUFFIX = ###;
public static final int SERVERPORT = ###;
public static final String SERVER_IP = ###;

private Socket socket;
String response;
String inputStr;

public ServerWork(String inputStr){
    this.inputStr = inputStr;
}

@Override
public void run() {
    try {
        InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
        socket = new Socket(serverAddr, SERVERPORT);

        String str = PREFIX  + inputStr + SUFFIX;
        PrintWriter printOut = new PrintWriter(new BufferedWriter(
                new OutputStreamWriter(socket.getOutputStream())),
                true);

        BufferedReader inputBuffer = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );

        printOut.println(str);
        printOut.flush();

        char buf[] = new char[ 1000 ];
        int count = inputBuffer.read( buf );
        response = new String( buf, 0, count );


    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

欢迎使用stackoverflow。请附上一些您已经尝试过的代码片段。当您说“后台线程”时,您是要求GUI具有交互性,还是希望在执行后台线程时阻止UI?最好的选择是使用异步任务,但是这会用一个对话框来阻止用户界面,该对话框决定了进度。如果您希望GUI具有交互性,请使用处理程序线程。如果您需要永久连接,则应在服务上执行这些异步任务操作。我认为您需要使用服务,然后将
绑定到该服务或发送
广播
,以便在服务和UI之间进行通信