Skip to content

Instantly share code, notes, and snippets.

@jaydeepw
Last active June 14, 2018 13:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jaydeepw/4201419 to your computer and use it in GitHub Desktop.
Save jaydeepw/4201419 to your computer and use it in GitHub Desktop.
Holding and releasing WiFi wake locks in android.
// 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