PDA

View Full Version : [Android] "WifiLock under-locked my_lock" error.



makzimi
04.06.2015, 12:49
Hello,

When I tried to use sdktool to download packages for offline usage my app was crashed with this error:


java.lang.RuntimeException: WifiLock under-locked my_lock
at android.net.wifi.WifiManager$WifiLock.release(Wifi Manager.java:2147)
at com.skobbler.ngx.sdktools.download.SKToolsDownload Performer.releaseResourcesWhenDownloadThreadFinish es(SKToolsDownloadPerformer.java:488)
at com.skobbler.ngx.sdktools.download.SKToolsDownload Performer.run(SKToolsDownloadPerformer.java:347)


I found already this issue here http://stackoverflow.com/questions/29675731/wifilock-under-locked-my-lock and I solved this problem for me.

But I suppose sdktool code has this bug, so I want to share it with you.

In SKToolsDownloadPerformer class WifiLock is created but never acquired.


if ((downloadListener != null) && (downloadListener instanceof Activity)) {
WifiManager wifimanager = (WifiManager) ((Activity) downloadListener).getSystemService(Context.WIFI_SE RVICE);
wifiLock = wifimanager.createWifiLock("my_lock");
}

So release() method throws an exception here:


private void releaseResourcesWhenDownloadThreadFinishes() {
// release the WI-FI lock
if (wifiLock != null) {
wifiLock.release();
}


The solution is to check isHeld() before do any release(), or to add acquire() right after creating the lock (or both).



if ((downloadListener != null) && (downloadListener instanceof Activity)) {
WifiManager wifimanager = (WifiManager) ((Activity) downloadListener).getSystemService(Context.WIFI_SE RVICE);
wifiLock = wifimanager.createWifiLock("my_lock");
wifiLock.acquire();
}




private void releaseResourcesWhenDownloadThreadFinishes() {
// release the WI-FI lock
if (wifiLock != null) {
if(wifiLock.isHeld()) {
wifiLock.release();
}
}


P.S. And don't forget to add
<uses-permission android:name="android.permission.WAKE_LOCK" /> in your Manifest.

Maxim.

Adela_Silvia
04.06.2015, 17:42
Thanks makzimi