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

前端 未结 13 744
庸人自扰
庸人自扰 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 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
                        }
                    }
                }
            };
        }
    

提交回复
热议问题