Wi-Fi 已打开,但没有互联网连接检查 Android

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

类 NetworkConnectivityObserver( 上下文:上下文, ): ConnectivityObserver {

private val connectivityManager =
    context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
private val networkRequest = NetworkRequest.Builder()
    .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
    .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
    .build()

override fun observe(): Flow<ConnectivityObserver.Status> {
    return callbackFlow {
        val callback = object : ConnectivityManager.NetworkCallback() {
            override fun onAvailable(network: Network) {
                super.onAvailable(network)
                launch { send(ConnectivityObserver.Status.Available) }
            }

            override fun onLosing(network: Network, maxMsToLive: Int) {
                super.onLosing(network, maxMsToLive)
                launch { send(ConnectivityObserver.Status.Losing) }
            }

            override fun onLost(network: Network) {
                super.onLost(network)
                launch { send(ConnectivityObserver.Status.Lost) }
            }

            override fun onUnavailable() {
                super.onUnavailable()
                launch { send(ConnectivityObserver.Status.Unavailable) }
            }
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            connectivityManager.registerDefaultNetworkCallback(callback)
        }else{
            connectivityManager.registerNetworkCallback(networkRequest, callback)
        }
        awaitClose {
            connectivityManager.unregisterNetworkCallback(callback)
        }
    }.distinctUntilChanged()
}}

我使用上面的代码来检查互联网连接,但只有当互联网打开/关闭时才会得到响应。

我想要我的设备 Wi-Fi 已打开但没有可用的互联网连接的解决方案或代码。

如果有人有的话请给我解决方案。

android kotlin wifi internet-connection mobile-data
1个回答
0
投票

您可以使用这个方法:

Constants.REACHABILITY_SERVER = "https://www.google.com"

fun hasInternetConnected(context: Context): Boolean {
    if (hasNetworkAvailable(context)) {
        try {
            val connection = URL(Constants.REACHABILITY_SERVER).openConnection() as HttpURLConnection
            connection.setRequestProperty("User-Agent", "ConnectionTest")
            connection.setRequestProperty("Connection", "close")
            connection.connectTimeout = 1000 // configurable
            connection.connect()
            Logger.d(classTag, "hasInternetConnected: ${(connection.responseCode == 200)}")
            return (connection.responseCode == 200)
        } catch (e: IOException) {
            Logger.e(classTag, "Error checking internet connection", e)
        }
    } else {
        Log.w(classTag, "No network available!")
    }
    Log.d(classTag, "hasInternetConnected: false")
    return false
}

该代码通过尝试建立与指定服务器(在本例中为“https://www.google.com”)的连接来检查互联网连接,然后检查响应代码。如果响应码为200,则返回true,表示连接成功。如果响应码不是200或者捕获到异常,则返回false

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