如果有新数据到达 Android,则从套接字读取数据
我有一个与服务器通信的应用程序。当新数据可用于获取时,我希望我的应用程序仅读取套接字的输入流。
目前,我创建了一个计时器,计划使用 java.nio.channels 的 SocketChannel 类每 20 毫秒(轮询)读取套接字的输入流。这不太好,因为即使没有可用数据,它也会最终读取套接字。而且它会快速耗尽电池。
是否有一个适用于 Android 的 API,每当有新数据可用时,它就会通知或向连接的客户端发送一个标志,以便这是我唯一读取输入流的时间?
I have an application that communicates to server. I want my application to READ ONLY the socket's inputstream when NEW DATA is available for fetching.
Currently, I create a timer that scheduled for the reading of socket's inputstream every 20ms(polling) using SocketChannel class of java.nio.channels. This is not that good because it will end up of reading the socket even if there's no available data. And it drains the battery fast.
Is there an API for Android that will tell or send a flag to the connected client whenever a new data is available so that it is the only time I will read the inputstream?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请参阅 this,但简短的答案是否定的,没有用于此的 API。顺便说一句,如果没有数据可用,SocketChannel/Selector 实际上不会读取套接字,只需检查其状态。
对于推送通知,您可以检查 Android 云到设备消息传递框架。
AFIAK,它以类似的方式实现:它们保持套接字打开,并发送通知
当可用时。它很可能已经针对低电池使用率进行了调整,并且是操作系统的一部分,因此可能值得一试(2.2 及更高版本)。
See this, but the short answer is no, there is no API for this. BTW, SocketChannel/Selector won't actually read the socket if not data is available, just check it's status.
For push notifications, you might check the Android Cloud to Device Messaging Framework.
AFIAK, it's implemented in a similar fashion: they keep a socket open, and send notifications
when available. It is most probably already tuned for low battery usage, and is part of the OS, so might be worth a try (2.2 and above).