Currently I have this in my code:
WifiManager.WifiLock wifiLock = ((WifiManager) context
.getSystemService(Context.WIFI_SERVICE))
.createWifiLock(WifiManager.WIFI_MODE_FULL, "MyWifiLock");
wifiLock.aquire();
However my app uses "any" type of network. When there's no Wifi connection it automatically uses 3G data. Is there a way to optimize this code somehow so that it only locks WiFi if it's actually being used? The only way I can think of doing it is to change the above code to something like:
PreferenceManager
.getDefaultSharedPreferences(getContext())
.edit()
.putBoolean(PREF_WIFI_LOCK_NEEDED, true)
.apply();
and creating some NetworkStateReceiver that listens to WifiManager.NETWORK_STATE_CHANGED_ACTION and/or ConnectivityManager.CONNECTIVITY_ACTION broadcasts and aquire/release the lock somehow (and probably saving the lock to a static member of my Application?)
Is there a recommended way to do this?