简体   繁体   中英

How to intercept connection to a Wifi network most efficiently on Android

I want to perform some action when the phone connects to a certain WiFi network. As far as I can see I have 2 Broadcast intent to intercept that will satisfy this: 1. Wifi State Changed. 2. Connectivity Changed.

The problem however is that I want to intercept ONLY the Wifi Connected events. Currently my Receiver is triggered on any change to the WiFi, including disconnection, which I don't really care about.I feel it is a waste of CPU time.

Are there any more specific intents, like "Wifi Connected"? Or alternatively, can I add something to the intent filter to achieve this?

Thanks!

You can determine the type of a network event by requesting his extra informations. First, make sure that you registered an IntentFilter on the WifiManager.NETWORK_STATE_CHANGED_ACTION action and bind it to a proper BroadcastReceiver .

Then in the receiver's onReceive method, you can check if the received event is a NetworkInfo.State.CONNECTED event :

@Override
public void onReceive(Context context, Intent intent) {    
  NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);

  if (networkInfo != null 
     && networkInfo.getState().equals(NetworkInfo.State.CONNECTED) ) {
     // Do whatever you want
  }
}

As far as I can say, there is no way to filter the intent WifiManager.NETWORK_STATE_CHANGED_ACTION by state (Connected / Disconnected) or by network name.

Too bad :(

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM