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 ?
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.