1

I am developing a standalone app for Samsung Galaxy watch 4. I am using internet to connect with webservice APIs. Samsung Galaxy watch 4 supports Wi-Fi connection but it gets switched to phone internet when watch is paired with a phone. So to check internet availability on watch, I have written below code

    fun isNetworkConnected(context: Context): Boolean {
    val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

    val n = cm.activeNetwork
    if (n != null) {
        val nc = cm.getNetworkCapabilities(n)
       
        //It will check for both WiFi and Bluetooth transport
        return (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ||
                nc.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH))
    }
    Log.d(TAG,"No Active Network Available")
    return false 
}

Issue with the above code is that when watch is paired with phone, and phone's mobile data & Wi-Fi is switch off and watch Wi-Fi is also switched off still nc.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH) returns true and my app crashes because actually there is no internet available. Can anyone has any idea to check internet availability in better way on app running on wear OS 3.0 ?

Nishant
  • 32,082
  • 5
  • 39
  • 53
  • "my app crashes because actually there is no internet available" -- that is a bug. You need to fix the bug. Your function only reports whether there is a network connection. It does not say whether the connection is useful for your app. The connection might be useless in general (e.g., corporate firewall mandating use of a proxy server, Roomba unplugged the router's WAN cable). Or, your server might be unreachable for other reasons (e.g., server crash, DNS issues), even though other sites are reachable. This function *at best* is useful for helping you advise the user how to fix the problem. – CommonsWare Sep 23 '21 at 12:42

1 Answers1

1

Your code is ok, but is intended for other purposes, not to check for internet connection only. I suggest you take a look to this documentation https://developer.android.com/training/wearables/data/network-access#requesting-wifi-connectivity

It may require a bit of rework on your end since it will be an async callback, but it is for your use case I think is the best approach.

val callback = object : ConnectivityManager.NetworkCallback() {
    override fun onAvailable(network: Network) {
        super.onAvailable(network)
        // The Wi-Fi network has been acquired, bind it to use this network by default
        connectivityManager.bindProcessToNetwork(network)
    }

    override fun onLost(network: Network) {
        super.onLost(network)
        // The Wi-Fi network has been disconnected
    }
}

connectivityManager.requestNetwork(
    NetworkRequest.Builder()
        .addTransportType(
            NetworkCapabilities.TRANSPORT_WIFI
        ).build(),
    callback
)
Sergio Pardo
  • 774
  • 6
  • 17