IntentService中的套接字监听器

时间:2015-06-10 21:06:28

标签: android sockets android-broadcast android-intentservice

在我的程序中,我通过IntentService类中的socket接收数据,然后将其作为广播发送到activity。 Activity处理输入并准备输出。

while (true) {

            socket = serverSocket.accept();

            //Read data from socket

            //Publishing as a broadcast }

现在我的问题是

  1. 如何将活动的输出发送到intentService? 我知道我可以向intentService发出一个新的意图,但由于我的while循环已经在无限循环中运行,因此不会排队并且可能永远不会执行吗?
  2. 即使我设法从活动中获取数据到intentService,我如何使用相同的套接字连接写回客户端,还是应该为它创建一个单独的线程?
  3. 任何见解都会有所帮助。

2 个答案:

答案 0 :(得分:1)

I think you should change your implementation as IntentService has only one thread and it is blocked with accept call. May be you should create two separate threads for accepting the connection and handling connected sockets. Using this approach you can easily share the data either using static objects or through broadcast receiver to the connected socket thread. Refer Bluetoothchat sample from android sdk.

答案 1 :(得分:1)

IntentService is the wrong choice for this behaviour. You should use a regular Service and manage the threads and connections yourself.

You can then send data from an Activity to the Service either by calling startService() with an Intent containing the data, or you can have your Activity bind to the Service and use AIDL (remote procedure calls).