在安卓Kotlin平台上检查网络连接存在问题

5
我在onCreate中调用以下函数,当我在该活动上打开和关闭设备的网络连接时,它可以完美地显示消息。然而,如果我在设备的网络关闭状态下打开此活动,则不会显示网络已关闭的消息,而当我在打开活动时有网络连接时,它会显示我已连接到网络的消息。
       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()
            }
        })
    }

以下是 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)
    }
}

展示一下 CheckConnectivity(application) - Sam Chen
问题已更新,请查看。 - Codist
1个回答

2
这可以通过调用onUnavailable()实现,但遗憾的是,该函数没有响应。请查看NetworkCallback's onUnavailable() method isn't called if no Wi-Fi AP are found
但是,您可以通过将isconnected()添加到您的MainActivity.kt中来完成此操作。我知道这不是您要寻找的答案,但通过这样做,您的问题将得到解决。祝您好运。
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
    }
}

是的,看起来我的问题已经解决了,但这种方法有没有什么缺点?谢谢。 - Codist
不,我从未遇到过activeNetworkInfo的任何问题,但由于他们将其弃用,可能会出现一些问题。我仍在使用它,而且它运行良好。https://developer.android.com/reference/android/net/NetworkInfo - Shoaib Kakal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接