检查Kotlin中的Internet连接android [英] Check internet connectivity android in kotlin

查看:88
本文介绍了检查Kotlin中的Internet连接android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了(可接受的答案).我可以使用"PING"方法,但是UI变黑了,因为它说它将阻塞UI线程.它看起来不好,令人不安,所以我尝试使用第二种方法连接到Internet上的套接字",但是我不知道如何在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.

这是android studio将Java转换为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".

我的问题是如何使用该课程?

推荐答案

以这种方式调用AsyncTask,它应该可以工作.您无需在InternetCheck AsyncTask中进行任何更改.基本上,您需要传递一个实现InternetCheck类中定义的Consumer接口的对象.

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")
    }
})

这篇关于检查Kotlin中的Internet连接android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆