Search code examples
javaandroidwifiandroid-wifi

How to detect when user turn one wifi connection to other wifi?


I have problem with WiFi connection detection. My goal is to detect when user is switching between different WiFis. I found this, but it only detects when WiFi was established. In my case I need to know when one WiFi network changed to another on phone.


Solution

  • You can use BroadcastReceiver

    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(intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
                    if(netInfo.isConnected()) {
                        WifiManager wifiManager = (WifiManager) context.getAplicationContext().getSystemService (Context.WIFI_SERVICE);
                        WifiInfo info = wifiManager.getConnectionInfo ();
                        String ssid  = info.getSSID();
                        Log.d("Wifi Connected", "Wifi name is "+ info.getSSID());
                    }
            }
        }
    }