In response to the sabsab. To connect to the relay of communication translation, I used the response of warbi 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); } 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 based 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 use 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) {
Note that the listener is deleted after the callback is triggered, because it is a static listener. In any case, this implementation works for me and is one way to capture your activity, or is it static somewhere.
Danuofr Nov 19 '16 at 1:17 2016-11-19 01:17
source share