我使用了connectivityManager.registerDefaultNetworkCallback 来检查互联网连接。我已经<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
在我的AndroidManifest.xml
我正在检查网络连接的变量,如
class App : Application() {
companion object {
lateinit var userDetails: PhoenixResponse
lateinit var userSocket: UserSocket
lateinit var userChannel: UserChannel
lateinit var chatChannel: UserChannel
var isNetworkConnected: Boolean = false
}
}
实用程序类的功能就像-
@RequiresApi(Build.VERSION_CODES.N)
fun registerDefaultNetworkCallback() {
try {
val connectivityManager =
(context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager)
connectivityManager.registerDefaultNetworkCallback(@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
object : NetworkCallback() {
override fun onAvailable(network: Network) {
super.onAvailable(network)
App.isNetworkConnected = true
Log.d("FLABS:", "onAvailable "+App.isNetworkConnected)
}
override fun onLost(network: Network) {
super.onLost(network)
App.isNetworkConnected = false
Log.d("FLABS:", "onLost")
}
override fun onBlockedStatusChanged(
network: Network,
blocked: Boolean
) {
super.onBlockedStatusChanged(network, blocked)
Log.d("FLABS:", "onBlockedStatusChanged")
}
override fun onCapabilitiesChanged(
network: Network,
networkCapabilities: NetworkCapabilities
) {
super.onCapabilitiesChanged(network, networkCapabilities)
Log.d("FLABS:", "onCapabilitiesChanged")
}
override fun onLinkPropertiesChanged(
network: Network,
linkProperties: LinkProperties
) {
super.onLinkPropertiesChanged(network, linkProperties)
Log.d("FLABS:", "onLinkPropertiesChanged")
}
override fun onLosing(network: Network, maxMsToLive: Int) {
super.onLosing(network, maxMsToLive)
Log.d("FLABS:", "onLosing")
}
override fun onUnavailable() {
super.onUnavailable()
Log.d("FLABS:", "onUnavailable")
}
}
)
} catch (e: Exception) {
Log.d("FLABS: Exception ", "hello")
App.isNetworkConnected = false
}
}
它正在输入OnAvailable()
方法并更新App.isNetworkConnected
变量。但是当我从我的活动中检查它时,它并没有反映这些变化——
val network = CheckNetwork(applicationContext)
network.registerDefaultNetworkCallback()
if (App.isNetworkConnected) {
// Internet Connected
Toast.makeText(applicationContext,"You are connected!",Toast.LENGTH_LONG).show()
} else {
Toast.makeText(applicationContext,"Network is not connected!",Toast.LENGTH_LONG).show()
// Not Connected
}
虽然我有活动的互联网连接,但它并没有改变
App.isNetworkConnected
fromfalse
的值 -true
每次它都显示为 false
任何帮助表示赞赏错误是什么以及使用它的正确方法应该是什么