Android 服务和操作之间的单例
我正在做一个项目。它将使用来自服务的 TCP 套接字连接到远程主机。并与其交互以获取和发送数据。
我计划的流程是;
单例套接字类。它返回一个已连接套接字引用;
询问用户远程服务器的 IP 和端口的活动。 由带有 ip:port 参数的活动触发的服务(意图)。 服务将使用单例套接字类获取套接字。 然后服务会读取数据;解析它并在新的操作窗口中向用户显示用户操作(预期)。 用户完成操作后;结果将发送到服务器。并将读取新的请求。
问题/疑问在这里;
当您返回服务进行第二次数据读取操作时;插座会在那里吗? (或垃圾收集) 因为在数据读取操作开始后,没有接受新的连接。
调用用户操作活动后第一个服务会终止吗?
如果我从活动、创建的新服务或现有的启动服务再次回调时使用 startService 调用服务,会发生什么?
我怎样才能让服务永远活下去,除非我说它死掉。
抱歉,如果我问了愚蠢的问题。
I am working on a project that. It will connect to a remote host using tcp sockets from a service. And interact with it for getting and sending data.
The flow, I have planned is;
a singleton socket class. Which returns a connected socket refference;
an activity to ask user for remote server's ip and port.
a service triggered(intent) by the activity with the parameters of ip:port.
service will get the socket using singleton socket class.
and then service will read a data; parse it and show user for user actions in a new action window ( intended).
after user completed the action; result will be sent to the server. and new request will be read.
problem/query is here;
when you come back to the service for second data read operation; will the socket be there ? (or garbage collected )
because after data read operation started no new connection accepted.will the first service die after calling the user actions activity ?
what happens if I call the service using startService from an activity, a new service created or the existing before started service called back again ?
how can I let the service live for ever unless I said it to die.
Sorry, If I am asking silly questions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我是这样看的:
如果对象是静态的并且将套接字作为成员变量,它很可能会在那里,您应该在单一模式中采取保护措施来避免此问题
(if single==null){...},您还可以尝试通过覆盖
Application
类并在其中添加工厂方法来管理它。您需要确保套接字正确打开和关闭,而不仅仅是挂起,因为这可能会产生问题编辑:
实际套接字是否仍然打开将取决于套接字的超时
需要告诉服务停止,这样它就不会消亡
如果服务正在运行,它不会创建另一个服务,它会调用正在运行的服务的
onStartCommand()
这是默认行为
Here's how I see it:
If the object is static and has the socket as a member variable it will most likely be there, you should have safeguards in your single pattern to shield from this problem
(if single==null){...}
, you could also try managing it by overriding theApplication
class and adding a factory method in there. You need to make sure the socket is open and closed correctly and not just left hanging as this could create problemsEDIT:
Whether the actual socket is still open will depend on the timeout of the socket
Services need to be told to stop and so it will not die
If the service is running, the it will not create another, it will call the
onStartCommand()
of the running serviceThis is default behavior