我必须实现一个应用程序.此应用程序使用TCP / IP与服务器通信.我的应用程序必须向服务器请求位置.因为应用程序必须保持监听服务器请求,我认为使用IntentService.所以我实现它:
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();
} } }
我想问你一些问题:
1. IntentService如何维护与服务器的TCP连接?
2.每隔5分钟,我必须向服务器发送“KEEP_ALIVE”消息.我可以把它放进去吗?
3.我已实现此任务以维持与服务器的连接;为了在服务器上调用位置,我是否要使用新线程(例如新类扩展Runnable)?
4.使用asynctask做同样的工作是不对的?
5.为了与主UT通信,我要实现一个RegisterReceiver,这是错误的?
谢谢您的帮助.