How to check internet connection before app starts and while it is running?

后端 未结 5 1457
一整个雨季
一整个雨季 2021-01-26 15:59

I found a lot of answer about this but unable to implement those also. I want to implement this code here but not able to do so.

This code I found on google documentatio

5条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-26 16:03

    UPDATE:

    Update the solution for internet checking. What works for me now is this

    fun isNetworkAvailable(context: Context?): Boolean {
        if (context == null) return false
    
        val connectivityManager =
            context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            val capabilities =
                connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
            return capabilities != null &&
                    (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
                            capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ||
                            capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET))
        } else {
            try {
                val activeNetworkInfo = connectivityManager.activeNetworkInfo
                return activeNetworkInfo != null && activeNetworkInfo.isConnected
            } catch (ignored: Exception) {
            }
        }
    
        return false
    }
    

    OLD:

    Simple function to check the internet connection

    protected boolean isOnline() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnected()) {
            return true;
        } else {
            return false;
        }
    }
    

    and in your AndroidManifest.xml you should add the permission

    
    

提交回复
热议问题