5

I'm writing an HTTP server for Android devices, implemented via NanoHTTPD.

A goal of mine is to have the device allow incoming connections even with the screen off.

I started small, with a persistent notification, thinking that would keep my app in memory and running in the background. After locking the device, I could keep navigating the webpages it serves up as long as I don't leave it alone for about a minute. Once I do, it totally stops responding.

I escalated my attempt by including a CPU partial wakelock, which made no difference. I then added a full WifiLock to keep the radio on, and finally, in desperation, a MulticastLock (I thought maybe it'd keep the radio listening for connections). Still, after not making any connections for about a minute, the device stops responding, even with all these locks.

Is there anything specific I can do to keep the device listening for incoming connections? It seems like hitting the device with periodic requests keeps it awake... can I somehow emulate this behavior programmatically? I cannot think of a way.

Thanks!

EDIT: for the purpose of this question, battery drain can be disregarded.

EDIT: NanoHTTPD is being run as a service, as well.

bob
  • 1,879
  • 2
  • 15
  • 27
  • what do you mean listening for incoming connections, is it like listening for incoming calls? i don't really understand the purpose of listening to a connection – Ahmad Sanie Jan 02 '15 at 11:40
  • @AhmadAlsanie I mean after a period of about 1 minute of inactivity, the device stops responding to all incoming network connections, even with wifilocks and wakelocks. Network as in wifi, not LTE. The purpose of listening to a connection is that it is a server, and that's what servers do. – bob Jan 02 '15 at 11:44
  • Did you ever figure this out? – Michael Sep 18 '15 at 02:13
  • I've figured this out now @Michael – Chris Dec 02 '15 at 23:17

1 Answers1

4

You need the following:

  • Foreground service
  • Wifi lock
  • CPU lock

Incomplete snippets (eg missing the services / relinquishing the locks):

    // Keep the CPU awake.
    powerManager = (PowerManager)getSystemService(Context.POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Httpd");
    wakeLock.acquire();

    // Keep the wifi awake.
    WifiManager wm = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
    wifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "Httpd");
    wifiLock.acquire();
Chris
  • 39,719
  • 45
  • 189
  • 235