Issue with checking network connectivity on android Kotlin

Viewed 1041

I call the following function in onCreate and when I turn on and off the network connection on my device while I am on this activity, it shows the message perfectly fine. However, when I open this activity while the network on my device is turned off, it doesn't show the message that the network is turned off whereas when I open the activity when the network is turned on, it shows the message that I am connected to the network.

       private fun checkConnection() {
        connectivity = CheckConnectivity(application)
        connectivity.observe(this, { isConnected ->
            if (isConnected) {
          Toast.makeText(this,"You are connected to the internet",Toast.LENGTH_SHORT).show()
            } else {
           Toast.makeText(this,"You are NOT connected to the internet",Toast.LENGTH_SHORT).show()
            }
        })
    }

Following is CheckConnectivity.kt

    class CheckConnectivity(private val connectivityManager: ConnectivityManager) :
    LiveData<Boolean>() {

    constructor(application: Application) : this(
        application.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    )

    private val networkCallback = @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    object: ConnectivityManager.NetworkCallback(){

        override fun onAvailable(network: Network) {
            super.onAvailable(network)
            postValue(true)
        }

        override fun onLost(network: Network) {
            super.onLost(network)
            postValue(false)
        }
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onActive() {
        super.onActive()
        val builder=NetworkRequest.Builder()
        connectivityManager.registerNetworkCallback(builder.build(),networkCallback)
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onInactive() {
        super.onInactive()
        connectivityManager.unregisterNetworkCallback(networkCallback)
    }
}
1 Answers

This can be done by calling onUnavailable() but sadly, that function is not responding. Check NetworkCallback's onUnavailable() method isn't called if no Wi-Fi AP are found

But you can do this by adding isconnected() into your MainActivity.kt. I know this is not the answer you are looking for but by doing this your problem will be solved cheers.

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        checkConnection()
    }


    override fun onStart() {
        super.onStart()
        Toast.makeText(this, if (isConnected()) "You are connected to the internet" else "You are NOT connected to the internet", Toast.LENGTH_SHORT
        ).show()
    }
    
    private fun checkConnection() {
        val connectivity = CheckConnectivity(application)
        connectivity.observe(this, { isConnected ->
            Log.d("testTag", "checkConnection: Observer Called")
            if (isConnected) {
                Toast.makeText(this, "You are connected to the internet", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "You are NOT connected to the internet", Toast.LENGTH_SHORT)
                    .show()
            }
        })
    }

    private fun isConnected(): Boolean {
        var connected = false
        try {
            val cm =
                applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val nInfo = cm.activeNetworkInfo
            connected = nInfo != null && nInfo.isAvailable && nInfo.isConnected

            return connected
        } catch (e: Exception) {
            Log.e("Connectivity Exception", e.message!!)
        }
        return connected
    }
}
Related