简体   繁体   中英

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 ?

Update: Since Android 10 the use of theNetWorkInfo class and its methods is obsolete, now you must use the ConectivityManager class and getNetworkCapabilities () method from NetworkCapabilities Class .

How to check connectivity in Android?

Kotlin :

fun isOnline(context: Context): Boolean {
    val connectivityManager =
        context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    if (connectivityManager != null) {
        val capabilities =
            connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
        if (capabilities != null) {
            if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                Log.i("Internet", "NetworkCapabilities.TRANSPORT_CELLULAR")
                return true
            } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                Log.i("Internet", "NetworkCapabilities.TRANSPORT_WIFI")
                return true
            } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) {
                Log.i("Internet", "NetworkCapabilities.TRANSPORT_ETHERNET")
                return true
            }
        }
    }
    return false
}

Java:

public static boolean isOnline(Context context) {
       ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

if (connectivityManager != null) {
       NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(connectivityManager.getActiveNetwork());
        if (capabilities != null) {
            if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                Log.i("Internet", "NetworkCapabilities.TRANSPORT_CELLULAR");
                return true;
            } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                Log.i("Internet", "NetworkCapabilities.TRANSPORT_WIFI");
                return true;
            }  else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)){
                Log.i("Internet", "NetworkCapabilities.TRANSPORT_ETHERNET");
                return true;
            }
        }
    }

return false;
}

both methods require the permissions:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET"/>

Check internet connectivity in android kotlin

fun isNetworkAvailable(context: Context?): Boolean {
    if (context == null) return false
    val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        val capabilities = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
        if (capabilities != null) {
            when {
                capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> {
                    return true
                }
                capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> {
                    return true
                }
                capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> {
                    return true
                }
            }
        }
    } else {
        val activeNetworkInfo = connectivityManager.activeNetworkInfo
        if (activeNetworkInfo != null && activeNetworkInfo.isConnected) {
            return true
        }
    }
    return false
}

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")
    }
})
 fun verifyAvailableNetwork(activity:AppCompatActivity):Boolean{
      val connectivityManager=activity.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
      val networkInfo=connectivityManager.activeNetworkInfo
      return  networkInfo!=null && networkInfo.isConnected
}

Add these permission on top in Manifest

   <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
   <uses-permission android:name="android.permission.INTERNET"/>

and this function should do the trick. It will return boolean based on its connectivity

fun isOnline(context: Context): Boolean {
    val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        val n = cm.activeNetwork
        if (n != null) {
            val nc = cm.getNetworkCapabilities(n)
    //It will check for both wifi and cellular network
            return nc!!.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) || nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
        }
        return false
    } else {
        val netInfo = cm.activeNetworkInfo
        return netInfo != null && netInfo.isConnectedOrConnecting
    }
}

It has a deprecated method as well as a latest one based on your api version.

Shortest version

val Context.isConnected: Boolean
    get() {
        return (getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager)
           .activeNetworkInfo?.isConnected == true
    }

Try this utility method to check for the availability of internet.

fun isNetworkAvailable(context: Context): Boolean {
        val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        var activeNetworkInfo: NetworkInfo? = null
        activeNetworkInfo = cm.activeNetworkInfo
        return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting
    }

Hope this helps.

I modified your class to this

internal class InternetCheck(private val onInternetChecked: (Boolean) -> Unit) : 
AsyncTask<Void, Void, Boolean>() {
 init {
     execute()
 }

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

 }

 override fun onPostExecute(internet: Boolean) {
     onInternetChecked(internet)
 }
}

So you could use lambda function and you also dont have to deal with null check in there:

InternetCheck{ internet-> Log.d("Connection", "Is connection enabled? "+internet) }

You can use it like this:

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

For more infos you can see this thread: https://youtrack.jetbrains.com/issue/KT-7770

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM