Search code examples
androidkotlin

Check internet connectivity android in kotlin


I tried the answer from this (the accepted answer). I can use the "PING" method but the UI went black since it says it will block the UI Thread. It didn't look good and was disturbing so I tried to use the second method "Connect to a Socket on the Internet" but I don't know how to use the class in Kotlin.

This is the result of converted Java to kotlin by android studio

package com.mockie.daikokuten.helpers

import android.os.AsyncTask.execute
import android.os.AsyncTask
import java.io.IOException
import java.net.InetSocketAddress
import java.net.Socket


internal class InternetCheck(private val mConsumer: Consumer) : AsyncTask<Void, Void, Boolean>() {
interface Consumer {
    fun accept(internet: Boolean?)
}

init {
    execute()
}

override fun doInBackground(vararg voids: Void): Boolean? {
    try {
        val sock = Socket()
        sock.connect(InetSocketAddress("8.8.8.8", 53), 1500)
        sock.close()
        return true
    } catch (e: IOException) {
        return false
    }

}

override fun onPostExecute(internet: Boolean?) {
    mConsumer.accept(internet)
}
}

but I DONT KNOW HOW TO USE IT. I tried this way:

InternetCheck{ internet-> Log.d("test", "asdasdas") }

It didnt work and results in an error. It says I have to pass "Consumer".

My question is How to use that class?


Solution

  • Call the AsyncTask this way, it should work. You don't need to change anything in your InternetCheck AsyncTask. Basically you need to pass in an object that implements the Consumer interface that's defined in the InternetCheck class.

    InternetCheck(object : InternetCheck.Consumer {
        override fun accept(internet: Boolean?) {
            Log.d("test", "asdasdas")
        }
    })