android 连接tcp连接,android – 使用Service的TCP连接

我必须实现一个应用程序.此应用程序使用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,这是错误的?

谢谢您的帮助.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值