Last active
June 14, 2018 13:47
-
-
Save jaydeepw/4201419 to your computer and use it in GitHub Desktop.
Holding and releasing WiFi wake locks in android.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// create a class member variable. | |
WifiManager.WifiLock mWifiLock = null; | |
/*** | |
* Calling this method will aquire the lock on wifi. This is avoid wifi | |
* from going to sleep as long as <code>releaseWifiLock</code> method is called. | |
**/ | |
private void holdWifiLock() { | |
WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE); | |
if( mWifiLock == null ) | |
mWifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, TAG); | |
mWifiLock.setReferenceCounted(false); | |
if( !mWifiLock.isHeld() ) | |
mWifiLock.acquire(); | |
} | |
/*** | |
* Calling this method will release if the lock is already help. After this method is called, | |
* the Wifi on the device can goto sleep. | |
**/ | |
private void releaseWifiLock() { | |
if( mWifiLock == null ) | |
Log.w(TAG, "#releaseWifiLock mWifiLock was not created previously"); | |
if( mWifiLock != null && mWifiLock.isHeld() ){ | |
mWifiLock.release(); | |
//mWifiLock = null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment