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


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Captcha
captcha
Reload