How to check currently internet connection is available or not in android

前端 未结 18 1290
轮回少年
轮回少年 2020-12-04 15:40

I want to execute my application offline also, so I need to check if currently an internet connection is available or not. Can anybody tell me how to check if internet is av

相关标签:
18条回答
  • 2020-12-04 15:59

    Use Below Code:

    private boolean isNetworkAvailable() {
      ConnectivityManager connectivityManager 
          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
      NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
      return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }
    

    if isNetworkAvailable() returns true then internet connection available, otherwise internet connection not available

    Here need to add below uses-permission in your application Manifest file

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    
    0 讨论(0)
  • 2020-12-04 16:01

    This function works fine...

    public void checkConnection()
        {
            ConnectivityManager connectivityManager=(ConnectivityManager)
    
                    this.getSystemService(Context.CONNECTIVITY_SERVICE);
    
    
      NetworkInfo wifi=connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    
    
     NetworkInfo  network=connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    
    
            if (wifi.isConnected())
            {
               //Internet available
    
            }
            else if(network.isConnected())
            {
                 //Internet available
    
    
            }
            else
            {
                 //Internet is not available
            }
        }
    

    Add the permission to AndroidManifest.xml

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    
    0 讨论(0)
  • 2020-12-04 16:02

    Also, be aware that sometimes the user will be connected to a Wi-Fi network, but that network might require browser-based authentication. Most airport and hotel hotspots are like that, so you application might be fooled into thinking you have connectivity, and then any URL fetches will actually retrieve the hotspot's login page instead of the page you are looking for.

    Depending on the importance of performing this check, in addition to checking the connection with ConnectivityManager, I'd suggest including code to check that it's a working Internet connection and not just an illusion. You can do that by trying to fetch a known address/resource from your site, like a 1x1 PNG image or 1-byte text file.

    0 讨论(0)
  • 2020-12-04 16:02

    Deprecated on API 29.

    getActiveNetworkInfo is deprecated only in API 29 . So we can use it in bellow 29.

    New code in Kotlin for All the API

    fun isNetworkAvailable(context: Context): Boolean {
        val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    
        // For 29 api or above
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            val capabilities = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork) ?: return false
            return when {
                capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ->    true
                capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) ->   true
                capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ->   true
                else ->     false
             }
        }
        // For below 29 api
        else {
            if (connectivityManager.activeNetworkInfo != null && connectivityManager.activeNetworkInfo!!.isConnectedOrConnecting) {
                return true
            }
        }
        return false
    }
    
    0 讨论(0)
  • 2020-12-04 16:02

    Use ConnectivityManager Service

    Source Link

    ...
    ...
    import android.net.ConnectivityManager;
    ....
    ....
    public class Utils {
    
       static ConnectivityManager connectivityManager;
       ....
       ....
    
        public static String isOnline(Context context) {
            JSONArray array = new JSONArray();
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("connected","false");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            try {
                connectivityManager = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
    
                NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
                Log.i("networkInfo", networkInfo.toString());
                jsonObject.put("connected",(networkInfo != null && networkInfo.isAvailable() &&
                        networkInfo.isConnected()));
                jsonObject.put("isAvailable",(networkInfo.isAvailable()));
                jsonObject.put("isConnected",(networkInfo.isConnected()));
                jsonObject.put("typeName",(networkInfo.getTypeName()));
                array.put(jsonObject);
                return array.toString();
    
    
            } catch (Exception e) {
                System.out.println("CheckConnectivity Exception: " + e.getMessage());
                Log.v("connectivity", e.toString());
            }
            array.put(jsonObject);
            return array.toString();
        }
    
    }
    
    0 讨论(0)
  • 2020-12-04 16:04

    try using ConnectivityManager

    ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
     return false
    

    Also Add permission to AndroidManifest.xml

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    
    0 讨论(0)
提交回复
热议问题