How to detect when WIFI Connection has been established in Android?

前端 未结 13 705
庸人自扰
庸人自扰 2020-11-22 05:34

I need to detect when I have network connectivity over WIFI. What broadcast is sent to establish that a valid network connection has been made. I need to validate that a v

相关标签:
13条回答
  • 2020-11-22 05:50

    Here is an example of my code, that takes into account the users preference of only allowing comms when connected to Wifi.

    I am calling this code from inside an IntentService before I attempt to download stuff.

    Note that NetworkInfo will be null if there is no network connection of any kind.

    private boolean canConnect()
    {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    
        boolean canConnect = false;
        boolean wifiOnly = SharedPreferencesUtils.wifiOnly();
    
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if(networkInfo != null)
        {
            if(networkInfo.isConnected())
            {
                if((networkInfo.getType() == ConnectivityManager.TYPE_WIFI) ||
                   (networkInfo.getType() != ConnectivityManager.TYPE_WIFI && !wifiOnly))
                {
                    canConnect = true;
                }
            }
        }
    
        return canConnect;
    }
    
    0 讨论(0)
  • 2020-11-22 05:51

    For me only WifiManager.NETWORK_STATE_CHANGED_ACTION works.

    Register a broadcast receiver:

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
    registerReceiver(broadcastReceiver, intentFilter);
    

    and receive:

    @Override
    public void onReceive(Context context, Intent intent) {
    
        final String action = intent.getAction();
    
        if(action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)){
            NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
            boolean connected = info.isConnected();
    
            //call your method
        }      
    }
    
    0 讨论(0)
  • 2020-11-22 05:55

    I have two methods to detect WIFI connection receiving the application context:

    1)my old method

    public boolean isConnectedWifi1(Context context) {
        try {
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();           
            if (networkInfo != null) {
                NetworkInfo[] netInfo = connectivityManager.getAllNetworkInfo();
                for (NetworkInfo ni : netInfo) {
                    if ((ni.getTypeName().equalsIgnoreCase("WIFI"))
                            && ni.isConnected()) {
                        return true;
                    }                   
                }
            }
            return false;
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
        return false;
    }
    

    2)my New method (I´m currently using this method):

    public boolean isConnectedWifi(Context context) {
             ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
             NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);     
             return networkInfo.isConnected();
    }
    
    0 讨论(0)
  • 2020-11-22 05:56

    You can register a BroadcastReceiver to be notified when a WiFi connection is established (or if the connection changed).

    Register the BroadcastReceiver:

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
    registerReceiver(broadcastReceiver, intentFilter);
    

    And then in your BroadcastReceiver do something like this:

    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();
        if (action.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)) {
            if (intent.getBooleanExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, false)) {
                //do stuff
            } else {
                // wifi connection was lost
            }
        }
    }
    

    For more info, see the documentation for BroadcastReceiver and WifiManager

    Of course you should check whether the device is already connected to WiFi before this.

    EDIT: Thanks to ban-geoengineering, here's a method to check whether the device is already connected:

    private boolean isConnectedViaWifi() {
         ConnectivityManager connectivityManager = (ConnectivityManager) appObj.getSystemService(Context.CONNECTIVITY_SERVICE);
         NetworkInfo mWifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);     
         return mWifi.isConnected();
    }
    
    0 讨论(0)
  • 2020-11-22 05:56

    Answer given by user @JPM and @usman are really very useful. It works fine but in my case it come in onReceive multiple time in my case 4 times so my code execute multiple time.

    I do some modification and make as per my requirement and now it comes only 1 time

    Here is java class for Broadcast.

    public class WifiReceiver extends BroadcastReceiver {
    
    String TAG = getClass().getSimpleName();
    private Context mContext;
    
    @Override
    public void onReceive(Context context, Intent intent) {
    
        mContext = context;
    
    
        if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
    
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = cm.getActiveNetworkInfo();
    
            if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI &&
                    networkInfo.isConnected()) {
                // Wifi is connected
                WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                String ssid = wifiInfo.getSSID();
    
                Log.e(TAG, " -- Wifi connected --- " + " SSID " + ssid );
    
            }
        }
        else if (intent.getAction().equalsIgnoreCase(WifiManager.WIFI_STATE_CHANGED_ACTION))
        {
            int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN);
            if (wifiState == WifiManager.WIFI_STATE_DISABLED)
            {
                Log.e(TAG, " ----- Wifi  Disconnected ----- ");
            }
    
        }
    }
    }
    

    In AndroidManifest

    <receiver android:name=".util.WifiReceiver" android:enabled="true">
            <intent-filter>
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
            </intent-filter>
        </receiver>
    
    
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    
    0 讨论(0)
  • 2020-11-22 05:56

    To detect WIFI connection state, I have used CONNECTIVITY_ACTION from ConnectivityManager class so:

        IntentFilter filter=new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(receiver, filter);
    

    and from your BroadCastReceiver:

        if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) {
            int networkType = intent.getIntExtra(
                    android.net.ConnectivityManager.EXTRA_NETWORK_TYPE, -1);
            if (ConnectivityManager.TYPE_WIFI == networkType) {
                NetworkInfo networkInfo = (NetworkInfo) intent
                        .getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                if (networkInfo != null) {
                    if (networkInfo.isConnected()) {
    
                        // TODO: wifi is connected
                    } else {
                        // TODO: wifi is not connected
                    }
                }
            }
    
        }
    

    ps:works fine for me:)

    0 讨论(0)
提交回复
热议问题