I’m developing an Android application.
I want to test how asynchronous sockets work on Android doing a simple echo client.
On Java tutorial I have found the following code:
import java.io.*;
import java.net.*;
public class EchoClient {
public static void main(String[] args) throws IOException {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket("taranis", 7);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: taranis.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: taranis.");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
Instead of reading form System.in I want to let users fill an EditText and when user tap on a button I want to send the text introduced by user on that EditText.
And also, I want to make it using an AsyncTask. The above code will be on AsyncTask.doBackground() method.
I want to do the following: a user introduces a text, then he taps on send button, then he waits to see the response. When I get the response from Echo Server I let the user to introduces a new text and the process start over. There is another button to close socket and end the program.
My problem is: how can I notify that there is text available to send? In other words, when user taps over the send button, what must I do to pass that text to AsyncTask?
An
AsyncTaskessentially lets you do the following things:In your case, it sounds like you’re not sending data to the task, but rather, you’re starting the task with a specified parameter.
If you look at the examples given in the AsyncTask documentation, you will see that the first parameter of the template definition is the set of parameters to start the task. In your case, you would probably want to use a
URL(or possibly simply String) parameter. When the user clicks the button, you start the task, download the stuff, and then publish the results to the UI thread!