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.
You need the following:
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With