0

I have a Service running, that opens a port and receives messages. It does so by opening a port and listening to it in an infinite loop. When the screen is off for a few minutes, I don't receive any messages anymore.

Right now, I try to stay awake by aquiring a WakeLock. But this doesn't seem to work and consumes a lot of battery. So how can I keep the infite loop running and maybe how do I achieve it with minimum battery consumption.

This isn't the real code, but this is how I try to achieve staying awake in standby mode.

MyService{
...
public void startListening(){

new Thread(new Runnable(){

 public void run(){
 PowerManager mgr = (PowerManager)c.getSystemService(Context.POWER_SERVICE);
 final WakeLock wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ListeningLock");

 new Thread(new Runnable(){

 public void run(){
   wakeLock.acquire()
   someClass.infiniteListeningLoop();
   wakeLock.release();
 }

 }).start();

 }).start();

}

}

Update

The WakeLock is not the problem. I periodically make a notification that the loop is still running and how many times it already ran. So the problem seems to be the socket. I catch all Exceptions, but there is none thrown. May Android close the port after a while of not receiving anything?

Simon
  • 53
  • 5
  • Just out of curiosity, why not use GCM? GCM is always listening and this way you don't have to poll. – Vic Vuci Apr 07 '14 at 17:24
  • I will consider that, but I would prefer to not have a third party server involved.. – Simon Apr 07 '14 at 17:33
  • You will of course need to use the wakelock. Presumably if you are listening for connections successfully, you are using wifi and not a mobile network. It seems that on Android the wifi radio will often shut down after a while if you do not make active use of it, so you might try sourcing a trivial amount of traffic periodically. Of course this approach wastes battery - hence the recommendation for something like GCM which uses tricks not directly accessible to you in order to be more power efficient. – Chris Stratton Apr 07 '14 at 20:02
  • I use wifi and mobile networks, depends on what the client is connected to. This works fine so far. The only problem is, that after a while of not receiving a package, the socket doesn't receive packages anymore. I guess Android closes the port, but I'm not sure right now what exactly is the problem. – Simon Apr 07 '14 at 20:28

0 Answers0