How to check Internet available on app running on wear OS 3 (Samsung Galaxy Watch 4)

514 views Asked by At

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 ?

1

There are 1 answers

0
Sergio Pardo On

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
)