1

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?

Jacesheck
  • 13
  • 5

1 Answers1

1

As the exception says you are trying to do a network call on main thread which is prohibited.

An easy way to fix this would be to make the function suspendable and switch to a background thread

private suspend fun hasConnection() {
    withContext(Dispatchers.IO) {
        var address: InetAddress = InetAddress.getByName("192.168.1.1")
        val timeout = 1500
        if (address.isReachable(timeout)){
            status.text = "Available"
        }else{
            status.text = "Disconnected"
        }
    }
}

When calling hasConnection() use lifecycleScope from Activity level to launch a coroutine which will call your hasConnection()

------------- Somewhere in your Activity -------------


lifecycleScope.launch {
    hasConnection()
}
georkost
  • 588
  • 6
  • 12