收听Internet更改(无网络检测)

时间:2018-12-11 19:52:38

标签: android

注册以下侦听器是否会在Internet连接更改时或仅在网络连接更改时通知您的应用?

即使手机仍连接到同一网络,我也需要在互联网打开或关闭时得到通知。

<receiver
        android:name="com.internetconnection_demo.InternetConnector_Receiver"
        android:enabled="true" >
        <intent-filter>

            <!-- Intent filters for broadcast receiver -->
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            <action android:name="android.net.wifi.STATE_CHANGE" />
        </intent-filter>
    </receiver>

1 个答案:

答案 0 :(得分:0)

如果您使用的是Lollipop(API 21)或更高版本,则我不会采用BroadcastReceiver路线。尝试这样的事情:

fun monitorWifiConnection() {
    var connectivityManager: ConnectivityManager = getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
    val builder = NetworkRequest.Builder()
            .addTransportType(android.net.NetworkCapabilities.TRANSPORT_WIFI)
    connectivityManager.registerNetworkCallback(builder.build(), getConnectivityManagerCallback())
}

private fun getConnectivityManagerCallback(): ConnectivityManager.NetworkCallback {
    connectivityManagerCallback = object : ConnectivityManager.NetworkCallback() {
        override fun onAvailable(network: Network?) {
            //Connected to wifi
        }

        override fun onLost(network: Network?) {
            //Lost connection to wifi
        }
    }
    return connectivityManagerCallback
}

通过排除NetworkCapabilities.TRANSPORT_CELLULAR选项和包括NetworkCapabilities.TRANSPORT_WIFI,您应该只获得有关wifi连接的通知。