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

前端 未结 13 707
庸人自扰
庸人自扰 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:56

    1) I tried Broadcast Receiver approach as well even though I know CONNECTIVITY_ACTION/CONNECTIVITY_CHANGE is deprecated in API 28 and not recommended. Also bound to using explicit register, it listens as long as app is running.

    2) I also tried Firebase Dispatcher which works but not beyond app killed.

    3) Recommended way found is WorkManager to guarantee execution beyond process killed and internally using registerNetworkRequest()

    The biggest evidence in favor of #3 approach is referred by Android doc itself. Especially for apps in the background.

    Also here

    In Android 7.0 we're removing three commonly-used implicit broadcasts — CONNECTIVITY_ACTION, ACTION_NEW_PICTURE, and ACTION_NEW_VIDEO — since those can wake the background processes of multiple apps at once and strain memory and battery. If your app is receiving these, take advantage of the Android 7.0 to migrate to JobScheduler and related APIs instead.

    So far it works fine for us using Periodic WorkManager request.

    Update: I ended up writing 2 series medium post about it.

    0 讨论(0)
  • 2020-11-22 06:02

    The best that worked for me:

    AndroidManifest

    <receiver android:name="com.AEDesign.communication.WifiReceiver" >
       <intent-filter android:priority="100">
          <action android:name="android.net.wifi.STATE_CHANGE" />
       </intent-filter>
    </receiver>
    

    BroadcastReceiver class

    public class WifiReceiver extends BroadcastReceiver {
    
       @Override
       public void onReceive(Context context, Intent intent) {
    
          NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
          if(info != null && info.isConnected()) {
            // Do your work. 
    
            // e.g. To check the Network Name or other info:
            WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            String ssid = wifiInfo.getSSID();
          }
       }
    }
    

    Permissions

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    
    0 讨论(0)
  • 2020-11-22 06:11

    I used this code:

    public class MainActivity extends Activity
        {
        .
        .
        .
        @Override
        protected void onCreate(Bundle savedInstanceState)
            {
            super.onCreate(savedInstanceState);
            .
            .
            .
            }
    
        @Override
        protected void onResume()
            {
            super.onResume();
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
            registerReceiver(broadcastReceiver, intentFilter);  
            }
    
        @Override
        protected void onPause()
            {
            super.onPause();
            unregisterReceiver(broadcastReceiver);
            }
    
        private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver()
            {
            @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))
                        {
                        // wifi is enabled
                        }
                    else
                        {
                        // wifi is disabled
                        }
                    }
                }
            };
        }
    
    0 讨论(0)
  • 2020-11-22 06:13

    For all those who enjoying CONNECTIVITY_CHANGE broadcast, please note this is no more fired when app is in background in Android O.

    https://developer.android.com/about/versions/o/background.html

    0 讨论(0)
  • 2020-11-22 06:14

    This code does not require permission at all. It is restricted only to Wi-Fi network connectivity state changes (any other network is not taken into account). The receiver is statically published in the AndroidManifest.xml file and does not need to be exported as it will be invoked by the system protected broadcast, NETWORK_STATE_CHANGED_ACTION, at every network connectivity state change.

    AndroidManifest:

    <receiver
        android:name=".WifiReceiver"
        android:enabled="true"
        android:exported="false">
    
        <intent-filter>
            <!--protected-broadcast: Special broadcast that only the system can send-->
            <!--Corresponds to: android.net.wifi.WifiManager.NETWORK_STATE_CHANGED_ACTION-->
            <action android:name="android.net.wifi.STATE_CHANGE" />
        </intent-filter>
    
    </receiver>
    

    BroadcastReceiver class:

    public class WifiReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
    /*
     Tested (I didn't test with the WPS "Wi-Fi Protected Setup" standard):
     In API15 (ICE_CREAM_SANDWICH) this method is called when the new Wi-Fi network state is:
     DISCONNECTED, OBTAINING_IPADDR, CONNECTED or SCANNING
    
     In API19 (KITKAT) this method is called when the new Wi-Fi network state is:
     DISCONNECTED (twice), OBTAINING_IPADDR, VERIFYING_POOR_LINK, CAPTIVE_PORTAL_CHECK
     or CONNECTED
    
     (Those states can be obtained as NetworkInfo.DetailedState objects by calling
     the NetworkInfo object method: "networkInfo.getDetailedState()")
    */
        /*
         * NetworkInfo object associated with the Wi-Fi network.
         * It won't be null when "android.net.wifi.STATE_CHANGE" action intent arrives.
         */
        NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
    
        if (networkInfo != null && networkInfo.isConnected()) {
            // TODO: Place the work here, like retrieving the access point's SSID
    
            /*
             * WifiInfo object giving information about the access point we are connected to.
             * It shouldn't be null when the new Wi-Fi network state is CONNECTED, but it got
             * null sometimes when connecting to a "virtualized Wi-Fi router" in API15.
             */
            WifiInfo wifiInfo = intent.getParcelableExtra(WifiManager.EXTRA_WIFI_INFO);
            String ssid = wifiInfo.getSSID();
        }
    }
    }
    

    Permissions:

    None
    
    0 讨论(0)
  • 2020-11-22 06:15

    You can start a wifi connection if you give the user a choice to override the normal behavior of asking each time.

    I choose to use three methods...

    public boolean isOnline() 
    {
     ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
     NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
     return (networkInfo != null && networkInfo.isConnected());
    }  
    

    This is quick check if there is an internet connect either Wifi or CellData. From here you can choose what action you want to take. Is it in Airplane mode needs to be checked also.

    On a separate thread. I set a variable IpAddress to = " " And poll until I have a valid an ip address.

      WifiManager wifi;
      wifi = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
      WifiInfo wifiInfo = wifi.getConnectionInfo();
      int ipAddress = wifiInfo.getIpAddress();
      String ip = null;
      ip = String.format("%d.%d.%d.%d",
      (ipAddress & 0xff),
      (ipAddress >> 8 & 0xff),
      (ipAddress >> 16 & 0xff),
      (ipAddress >> 24 & 0xff));
      Log.e(" >>IP number Begin ",ip);
    

    Another code snippet... If its not on turn it on (with users prior permission)

       if(wifi.isWifiEnabled()!=true)wifi.setWifiEnabled(true);  
    
    0 讨论(0)
提交回复
热议问题