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

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

    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:)

提交回复
热议问题