在Android中监听网络连接的简单方法

在Android中监听网络连接的简单方法

在Android中监听网络连接的简单方法_第1张图片
要使用 Kotlin 监控 Android 中的互联网连接,您可以使用该类ConnectivityManager,这是一个允许您查询网络状态的系统服务。以下是如何使用它的示例:

  1. 将以下权限添加到您的 AndroidManifest.xml 文件:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  1. 创建一个监控网络状态的类:
class NetworkMonitor(context: Context) {

    private val connectivityManager =
        context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

    fun isNetworkAvailable(): Boolean {
        val networkInfo = connectivityManager.activeNetworkInfo
        return networkInfo != null && networkInfo.isConnected
    }
    
    fun registerNetworkCallback(networkCallback: ConnectivityManager.NetworkCallback) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            connectivityManager.registerDefaultNetworkCallback(networkCallback)
        } else {
            val builder = NetworkRequest.Builder()
            connectivityManager.registerNetworkCallback(builder.build(), networkCallback)
        }
    }

    fun unregisterNetworkCallback(networkCallback: ConnectivityManager.NetworkCallback) {
        connectivityManager.unregisterNetworkCallback(networkCallback)
    }
}

在上面的类中,我们创建了三个函数:

  • isNetworkAvailable():此功能检查设备是否连接到互联网。它返回一个布尔值。
  • registerNetworkCallback():此函数注册一个NetworkCallback对象来监听网络状态变化。它以一个NetworkCallback对象作为参数。
  • unregisterNetworkCallback():此函数取消注册以前注册的NetworkCallback对象。它以一个NetworkCallback对象作为参数。
  1. 创建NetworkCallback监听网络状态变化的对象:
val networkCallback = object : ConnectivityManager.NetworkCallback() {

    override fun onAvailable(network: Network) {
        // Called when a network is available
    }

    override fun onLost(network: Network) {
        // Called when a network is lost
    }
}
  1. NetworkCallbackNetworkMonitor类注册对象:
val networkMonitor = NetworkMonitor(context)
networkMonitor.registerNetworkCallback(networkCallback)
  1. 最后,不要忘记NetworkCallback在不再需要时注销该对象:
networkMonitor.unregisterNetworkCallback(networkCallback)
  • 使用BroadcastReceiver检查网络连接事件:
class ConnectivityReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        val connectivityManager =
            context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val networkInfo = connectivityManager.activeNetworkInfo
        if (networkInfo != null && networkInfo.isConnected) {
            // internet connection is available
        } else {
            // internet connection is not available
        }
    }
}

使用回调接口在网络连接发生变化时发出通知:

interface ConnectivityListener {
    fun onConnectivityChanged(isConnected: Boolean)
}

class ConnectivityMonitor(private val context: Context) {

    private val connectivityManager =
        context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

    private val callbackList = mutableListOf<ConnectivityListener>()

    private val connectivityCallback = object : ConnectivityManager.NetworkCallback() {
        override fun onAvailable(network: Network) {
            notifyListeners(true)
        }

        override fun onLost(network: Network) {
            notifyListeners(false)
        }
    }

    fun registerListener(listener: ConnectivityListener) {
        callbackList.add(listener)
    }

    fun unregisterListener(listener: ConnectivityListener) {
        callbackList.remove(listener)
    }

    fun startMonitoring() {
        val builder = NetworkRequest.Builder()
        connectivityManager.registerNetworkCallback(builder.build(), connectivityCallback)
    }

    fun stopMonitoring() {
        connectivityManager.unregisterNetworkCallback(connectivityCallback)
    }

    private fun notifyListeners(isConnected: Boolean) {
        for (listener in callbackList) {
            listener.onConnectivityChanged(isConnected)
        }
    }
}

  • 使用像RxAndroid这样的库来监控网络连接:
class MainActivity : AppCompatActivity() {

    private val connectivityObservable = ConnectivityObservable()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        connectivityObservable.observe(this)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe { isConnected ->
                if (isConnected) {
                    // internet connection is available
                } else {
                    // internet connection is not available
                }
            }
    }

    override fun onDestroy() {
        super.onDestroy()
        connectivityObservable.stopObserving(this)
    }
}

参考链接

https://medium.com/@manuchekhrdev/simple-ways-to-monitor-internet-connectivity-in-android-a3bef75bd3d9

你可能感兴趣的:(Android架构,Kotlin进阶,android,kotlin,android,studio)