3

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?

Khushbu Shah
  • 1,603
  • 3
  • 27
  • 45

1 Answers1

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).

Community
  • 1
  • 1
Nikolay Elenkov
  • 52,576
  • 10
  • 84
  • 84