Get immediate access to this and over 1,500+ other videos and books.

Boost your skills with a raywenderlich.com Beginner subscription. With over 60+ video courses and our core foundational programming books bundled in one subscription, it’s simply the best investment you can make in your development career.

Connect to the Internet

The student materials have been reviewed and are updated as of July 2022.

Add the required permissions to the Android Manifest file, and implement a way to check if the device is connected to the Internet.

Contributors

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.

Fetching data from a server requires an Internet connection.

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
class NetworkStatusChecker(private val connectivityManager: ConnectivityManager?) {

}
class NetworkStatusChecker(private val connectivityManager: ConnectivityManager?) {

  inline fun performIfConnectedToInternet(action: () -> Unit) {
    if (hasInternetConnection()) {
      action()
    }
  }
}
class NetworkStatusChecker(private val connectivityManager: ConnectivityManager?) {

  inline fun performIfConnectedToInternet(action: () -> Unit) {
    if (hasInternetConnection()) {
      action()
    }
  }

  // HERE
  fun hasInternetConnection(): Boolean {
    val network = connectivityManager?.activeNetwork ?: return false
    val capabilities = connectivityManager.getNetworkCapabilities(network) ?: return false
  }
}
class NetworkStatusChecker(private val connectivityManager: ConnectivityManager?) {

  inline fun performIfConnectedToInternet(action: () -> Unit) {
    if (hasInternetConnection()) {
      action()
    }
  }

  // HERE
  fun hasInternetConnection(): Boolean {
    val network = connectivityManager?.activeNetwork ?: return false
    val capabilities = connectivityManager.getNetworkCapabilities(network) ?: return false

    return capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
        || capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
        || capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)
  }
}

Reviews

Comments