I have to implement an application. This application communicates with a server using TCP/IP.My application has to request the position to a server.Because the application must stay to listen server request, I think to use an IntentService. So I implement it:
public class Tasks extends IntentService{
public final int SERVERPORT = 8100;
private Socket socket;
PrintWriter out;
BufferedReader in;
public Tasks()
{
super("My task!");
}
protected void onHandleIntent(Intent intent)
{
try
{
InetAddress serverAddr = InetAddress.getByName("10.0.0.138");
socket = new Socket(serverAddr, SERVERPORT);
out = new PrintWriter(socket.getOutputStream());
//send the request to authenticate it
out.print("Hello man");
out.flush();
//now i need to receive the request Hello_ACK
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String mServerMessage = in.readLine();
if(mServerMessage.equals("Hello_ACK"))
Log.d("show","connection completed");
//now how can I send KEEP_ALIVE message to server?
out.print("KEEP_ALIVE");
out.flush();
}
catch (IOException e)
{
e.printStackTrace();
} } }
I want to ask you some questions: 1. how IntentService maintain the TCP connection with the server? 2. every 5 minutes I have to send "KEEP_ALIVE" message to the server..how can I put it? 3.I've implemented this task for maintain the connection with the server; for calling position at the server, Have i to use a new thread (for examples a new class extends Runnable)? 4. is it wrong using an asynctask for doing the same work? 5. for communicate with the main UT, I have to implement a RegisterReceiver, it is wrong? Thank you for your help.