In response to sabsab. To hook into the Connectivity Change broadcast receiver I utilized warbi's answer and added a class with static methods.
public class WifiHelper
{
private static boolean isConnectedToWifi;
private static WifiConnectionChange sListener;
public interface WifiConnectionChange {
void wifiConnected(boolean connected);
}
/**
* Only used by Connectivity_Change broadcast receiver
* @param connected
*/
public static void setWifiConnected(boolean connected) {
isConnectedToWifi = connected;
if (sListener!=null)
{
sListener.wifiConnected(connected);
sListener = null;
}
}
public static void setWifiListener(WifiConnectionChange listener) {
sListener = listener;
}
}
Then I made changes to the receiver class on the first answer shown above.
public class ConnectivityReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMan.getActiveNetworkInfo();
if (netInfo != null && netInfo.getType() == ConnectivityManager.TYPE_WIFI)
{
Log.d("WifiReceiver", "Have Wifi Connection");
WifiHelper.setWifiConnected(true);
} else
{
Log.d("WifiReceiver", "Don't have Wifi Connection");
WifiHelper.setWifiConnected(false);
}
}
}
Finally, in your activity you can add a listener to utilize this callback.
wifiManager = (WifiManager) getContext().getSystemService(Context.WIFI_SERVICE);
wasWifiEnabled = (wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED || wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING);
WifiHelper.setWifiListener(new WifiHelper.WifiConnectionChange()
{
@Override
public void wifiConnected(boolean connected)
{
//Do logic here
}
});
Notice the listener is removed after the callback fires, this is because it's a static listener. Anyhow this implementation works for me and is one way to hook into your activity, or anywhere gives it's static.