简体   繁体   中英

When my android app is coming to foreground sometimes ConnectivityManager.activeNetwork object is null even when there is a good internet connection

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

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"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM