问题
I need to pull data from a server on the local network every x minutes via WiFi and HTTP. A Service is running in the Background and I use an AlarmManager to trigger the query. Wifi Sleep Policy is set to "never" on the device.
Problem is, the device goes to sleep when the screen is off and the wifi lock does not seem to reconnect the wifi properly, so the query fails.
Any idea what is wrong here ?
Exectution
{...}
wakeLockUtil.lock();
//wait for wifi to connect (no idea if this is useful)
Thread.sleep(3000);
doQuery();
wakeLockUtil.unlock();
{...}
WakeLock
public WakeLockUtil(Context context) {
wifiLock = ((WifiManager) context.getSystemService(Context.WIFI_SERVICE)).createWifiLock(WifiManager.WIFI_MODE_FULL,
"PeriodUpdateWifiLock");
wakeLock = ((PowerManager) context.getSystemService(Context.POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"PeriodUpdateWakeLock");
}
public void lock() {
System.out.println("WakeLockUtil.lock()");
try {
wakeLock.acquire();
wifiLock.acquire();
} catch (Exception e) {
Log.e(this.getClass().getSimpleName(), "Error getting Lock: " + e.getMessage());
}
}
public void unlock() {
System.out.println("WakeLockUtil.unlock()");
if (wakeLock.isHeld())
wakeLock.release();
if (wifiLock.isHeld())
wifiLock.release();
}
回答1:
I have seen issues on some devices where combination of PARTIAL_WAKE_LOCK and WifiLock:WIFI_MODE_FULL_HIGH_PERF does not fully work when screen is off. Very annoying. Only solution so far for me is to use SCREEN_DIM_WAKE_LOCK.
来源:https://stackoverflow.com/questions/14608658/android-wifilock-not-working