Reputation: 35
I am working on android app where I need to check for internet connection if available I hit the api inside onStart method else No-Internet popup opens. But sometimes(not everytime) when my app comes to foreground after hitting home button and then reopening the app ConnectivityManager.activeNetwork object is null. Why would this might happen or what approach I can follow to escape this problem. Can I delay the api request using handler?
Following is my method to check internet connection. When I call this method in onStart "cm" object is null sometimes hence opening no-internetpopup.
fun isConnected(): Boolean {
val cm = instance.getSystemService(Context.CONNECTIVITY_SERVICE) as
ConnectivityManager
if (cm != null) {
if (Build.VERSION.SDK_INT < 23) {
val ni = cm.activeNetworkInfo
if (ni != null) {
return (ni.isConnected && (ni.type == ConnectivityManager.TYPE_WIFI
|| ni.type == ConnectivityManager.TYPE_MOBILE
|| ni.type == ConnectivityManager.TYPE_BLUETOOTH))
}
} else {
Log.d("no_internet", "1" + cm.activeNetwork)
val n = cm.activeNetwork
if (n != null) {
val nc = cm.getNetworkCapabilities(n)
if (nc != null) {
return (nc.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
|| nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
|| nc.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH))
}
}
}
}
return false
}
Note:This issue occurs in some devices with o/s android 11, specifically samsung SM-M315F
Upvotes: 0
Views: 257
Reputation: 1
this only occurs when you use the method on onStart?
Maybe you should check you Manifest for <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Upvotes: 0