Search code examples
androidbroadcastreceiverandroid-wifi

Get WIFI ID from last connected WIFI


I'm writing an Android application which should react if the phone connects or disconnects to a WIFI network. I registered a BroadcastReceiver for this and it works great. Now with this code I'm able to get the current WIFI ID if the phone is connected to a WIFI:

WifiManager mainWifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo currentWifi = mainWifi.getConnectionInfo();

int id = currentWifi.getNetworkId();

But what if the WIFI disconnects and I want to get the WIFI ID of the last connected WIFI? My problem is that all this is in an BroadcastReceiver. This is allways new created if a new Broadcast comes in so I can not really save some data there. Is there a method or something else with which I can get the last connected WIFI ID?


Solution

  • Forgive me if I'm missing something. You could getSharedPreferences to have a context to access from Broadcast receiver.

    This BroadcastReceiver intercepts the android.net.ConnectivityManager.CONNECTIVITY_ACTION, which indicates a connection change. It checks whether the type is TYPE_WIFI. If it is, it checks whether Wi-Fi is connected and sets the wifiConnected flag in the main activity accordingly.

    public class NetworkReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager connMgr =
                    (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    
            // Checks the user prefs and the network connection. Based on the result, decides
            // whether
            // to refresh the display or keep the current display.
            // If the userpref is Wi-Fi only, checks to see if the device has a Wi-Fi connection.
            if (WIFI.equals(sPref) && networkInfo != null
                    && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                // If device has its Wi-Fi connection, sets refreshDisplay
                // to true. This causes the display to be refreshed when the user
                // returns to the app. 
    

    You can find here the sample app.