简体   繁体   中英

Is there a listener for when a user gets connected to a WiFi network (with internet access)?

I'm struggling to get to know when a user gets connected to a WiFi network with Internet access .

So far, I've tried two ways to achieve that:

  • using a BroadcastReceiver (action: android.net.conn.CONNECTIVITY_CHANGE ), and;
  • registering a NetworkCallback on ConnectivityManager .

Both of them fail most of the times since their callbacks are called too soon, because they are called while the network has no Internet access.

Is there a way to achieve what I want (for APIs >= 16)?

What I will suggest is to use ConnectivityManager to monitor connectivity status by implementing the following codes

ConnectivityManager cm =
        (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo activeNetwork = cm.getActiveNetworkInfo();


boolean isConnected = activeNetwork != null &&
                      activeNetwork.isConnected();

For more information please check the android Developer guide here

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