Search code examples
javaandroidconnectivitywifi

How to check for availability of a specific network type in android?


I wrote an android app, which requires large amount of data to be transfered via the network. To keep the invoices low, I added a switch in my config, which should switch the app to "wlan only" mode.

Unluckily I was unable to implement the correct check for a WLAN connection in my app, the basic idea was adding the needed permissions via

  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

in my manifest (which should suffice for this purpose) and implemented a simple method which is accessed in my activity:

protected boolean checkForNetwork(Context context, boolean wlanOnly) {
    // check via ACCESS_NETWORK_STATE
    ConnectivityManager manager = (ConnectivityManager) context.
            getSystemService(Context.CONNECTIVITY_SERVICE);
    if (!wlanOnly) {
        return manager.getActiveNetworkInfo().isConnected();
    } else {
        // hmm... 
    }
}

I'm pretty unsure what goes into the // hmm... part.


Solution

  • Try this:

    NetworkInfo info = manager.getActiveNetworkInfo();
    if (info.getType() == ConnectivityManager.TYPE_WIFI) {
        return info.isConnected();
    }