android开发 监听wifi的连接状态的kotlin代码
时间: 2023-10-08 22:06:30 浏览: 206
以下是 Kotlin 代码示例,用于检测 WiFi 连接状态的更改:
```kotlin
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.net.NetworkInfo
import android.net.NetworkRequest
import android.net.wifi.WifiInfo
import android.net.wifi.WifiManager
import android.os.Build
import android.util.Log
class WifiStateReceiver : BroadcastReceiver() {
private var wifiManager: WifiManager? = null
private var connectivityManager: ConnectivityManager? = null
private var networkCallback: ConnectivityManager.NetworkCallback? = null
override fun onReceive(context: Context, intent: Intent) {
wifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (wifiManager?.isWifiEnabled == true) {
Log.d(TAG, "WiFi is enabled.")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
networkCallback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: android.net.Network) {
super.onAvailable(network)
Log.d(TAG, "WiFi is connected.")
}
override fun onLost(network: android.net.Network) {
super.onLost(network)
Log.d(TAG, "WiFi is disconnected.")
}
}
val builder = NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
connectivityManager?.registerNetworkCallback(builder.build(), networkCallback!!)
} else {
context.registerReceiver(this, IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION))
}
} else {
Log.d(TAG, "WiFi is disabled.")
}
}
companion object {
private const val TAG = "WifiStateReceiver"
}
}
```
在 `onReceive()` 方法中,我们检查 WiFi 是否已启用。如果是,则根据设备的 Android 版本注册网络回调或广播接收器以监听网络状态更改。
如果 Android 版本大于或等于 N,我们将创建一个 `NetworkRequest` 并将其传递给 `registerNetworkCallback()` 方法以注册网络回调。在回调中,我们将检查网络是否可用,并相应地记录连接或断开连接的状态。
如果 Android 版本低于 N,则我们将注册一个广播接收器以侦听 `WifiManager.NETWORK_STATE_CHANGED_ACTION` 意图。在接收器中,我们将检查网络信息是否可用,并相应地记录连接或断开连接的状态。
阅读全文