Kotlin中没有Internet警报框

问题描述 投票:0回答:1

我刚刚开始学习Kotlin,我目前正在开发基于WebView的应用程序,如果打开应用程序后互联网不可用,我需要显示一个警告框。如何在Kotlin中做到这一点?

注:我已经检查了很多Stack Overflow问题,但是所有答案都是针对Java而非Kotlin的。另外,我只是一个初学者,所以请以简单的方式写下答案,以便我理解。对不起,英语不好

android android-studio kotlin webview alert
1个回答
0
投票
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager

open class ConnectionCheck:BroadcastReceiver() {

    override fun onReceive(context: Context?, intent: Intent?) {
        if (connectivityReceiverListener != null) {
            connectivityReceiverListener!!.onNetworkConnectionChanged(
                isConnectedOrConnecting(
                    context!!
                )
            )
        }
    }

    private fun isConnectedOrConnecting(context: Context): Boolean {
        val connMgr = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val networkInfo = connMgr.activeNetworkInfo
        return networkInfo != null && networkInfo.isConnectedOrConnecting
    }

    interface ConnectivityReceiverListener {
        fun onNetworkConnectionChanged(isConnected: Boolean)
    }

    companion object {
        var connectivityReceiverListener: ConnectivityReceiverListener? = null
    }
}

这是互联网连接活动。在您要检查Internet连接的每个活动中,该活动应扩展为ConnectionCheck.ConnectivityReceiverListener

不要忘记放清单中的<uses-permission android:name="android.permission.INTERNET"/>

© www.soinside.com 2019 - 2024. All rights reserved.