Reputation: 1024
I have used connectivityManager.registerDefaultNetworkCallback to check for internet connection.
I have given <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
in my AndroidManifest.xml
I am keeping an check on a variable for network connectivity , as
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
}
}
And the utility class's function is like-
@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
}
}
It is entering in OnAvailable()
method and updating the App.isNetworkConnected
variable.
But when I am checking it from my activity it is not reflecting the changes-
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
}
Though I have active Internet connection still it is not changing the value of
App.isNetworkConnected
fromfalse
totrue
-Everytime it is showing false
Any help is appreciated what the error is and what should be the proper way to use it
Upvotes: 0
Views: 348