Android网络监听不过时

原理:通过 ConnectivityManager注册网络监听回调。

import android.app.Application
import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.os.Build

class MyApplication: Application() {

    companion object {
        lateinit var instance: MyApplication
        // 是否有网络
        var hasNetwork = true
        // 是否蜂窝网络
        var isCellular = false
    }

    override fun onCreate() {
        super.onCreate()
        initApplication()
    }

    private fun initApplication() {
        instance = this
        // 注册网络监听
        registerNetworkObserver()
    }

    /**
     * 注册网络监听
     */
    private fun registerNetworkObserver() {
        (getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).apply {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                registerDefaultNetworkCallback(MyNetworkCallback)
            } else {
                registerNetworkCallback(
                    NetworkRequest.Builder()
                        .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
                        .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                        .build(),
                    MyNetworkCallback
                )
            }
        }
    }

    /**
     * 取消注册网络监听
     */
    private fun unregisterNetworkObserver() {
        (getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).apply {
            unregisterNetworkCallback(MyNetworkCallback)
        }
    }

    /**
     * 网络监听回调
     */
    object MyNetworkCallback : ConnectivityManager.NetworkCallback() {

        override fun onLost(network: Network) {
            super.onLost(network)
            // 网络丢失
            hasNetwork = false
        }

        override fun onCapabilitiesChanged(
            network: Network,
            networkCapabilities: NetworkCapabilities
        ) {
            super.onCapabilitiesChanged(network, networkCapabilities)
            val netKey = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                NetworkCapabilities.NET_CAPABILITY_VALIDATED
            } else {
                NetworkCapabilities.NET_CAPABILITY_INTERNET
            }
            // 网络状态变更
            hasNetwork = networkCapabilities.hasCapability(netKey).apply {
                // 是否蜂窝网络
                isCellular = this && networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
            }
        }
    }

    /**
     * 释放监听
     */
    fun release() {
        unregisterNetworkObserver()
    }
}

你可能感兴趣的:(Android工具类,安卓,Android,网络监听)