The WIFI_SERVICE must be looked up on the Application context...

Issue

Generating signed APK in Android Studio 2.3 fails with following error:

Error: The WIFI_SERVICE must be looked up on the Application context or memory will leak on devices < Android N. Try changing  to .getApplicationContext()  [WifiManagerLeak]

Resolution

As the error suggest it seems that WiFiManager must use Application Context (not Activity Context), otherwise a memory leak can occur. The error was triggered by following code:

 
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
 

To fix the issue I replaced the above line with:

 
WifiManager wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
 

February 2017
Android Studio 2.3



Newsletter

Subscribe to receive occasional updates on new posts.
Your email will not be used for any other purpose and you can unsubscribe at any time.
Please wait