Hi I am very new to android studio and a lot seems to have changed with Kotlin. Most of what I have found online is depcrecated.
I am simply trying to see if a device is connected to the network, just like the ping command in windows command prompt. This hasConnection()
function should change some text on the screen. I am just trying to get it to work with anything.
import java.net.InetAddress
...
private fun hasConnection() {
var address: InetAddress = InetAddress.getByName("192.168.1.1")
val timeout = 1500
if (address.isReachable(timeout)){
status.text = "Available"
}else{
status.text = "Disconnected"
}
}
I have added these two permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
The code was running, but showing disconnected and now it won't run at all without crashing. I am receiving the error android.os.NetworkOnMainThreadException
when address.isReachable()
is executed. Am I doing this right at all or is there a better way to do this?