Detect if Android device has Internet connection

后端 未结 15 2751
野性不改
野性不改 2020-11-22 08:54

I need to tell if my device has Internet connection or not. I found many answers like:

private boolean isNetworkAvailable() {
    ConnectivityManager connect         


        
15条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 09:51

    You can do this with very simple class.

    class CheckInternet {
        fun isNetworkAvailable(context: Context): Boolean {
            val connectivityManager =
                context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
            val activeNetworkInfo = connectivityManager!!.activeNetworkInfo
            return activeNetworkInfo != null && activeNetworkInfo.isConnected
        }
    }
    

    Now you can check this from any class.

    if (CheckInternet().isNetworkAvailable(this)) {
      //connected with internet
    }else{
      //Not connected with internet
    }
    

提交回复
热议问题