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

后端 未结 5 1425
一整个雨季
一整个雨季 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

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    
    0 讨论(0)
  • 2021-01-26 16:08
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (activeNetwork != null) {
            if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
                return true;
            } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
                return true;
            }
        }
        return false;
    }
    
    0 讨论(0)
  • 2021-01-26 16:08

    like this you can make this method in your common file for your project

     public static boolean isNetworkAvailable(Context ctx) {
        ConnectivityManager cm = (ConnectivityManager) ctx
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()
                && cm.getActiveNetworkInfo().isAvailable()
                && cm.getActiveNetworkInfo().isConnected()) {
            return true;
        } else {
            return false;
        }
    }
    

    and use like

    if(commonfile.isNetworkAvilable(pass your context here))
    {
      //call your method
    }
    

    and don't forgot to add permission for Internet in your manifeast

    0 讨论(0)
  • 2021-01-26 16:12
     protected boolean isNetworkAvilable() {
            boolean isNetworkAvilable = false;
            ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = manager.getActiveNetworkInfo();
            if (info != null && info.isAvailable() && info.isConnected()) {
                isNetworkAvilable = true;
            }
            return isNetworkAvilable;
        }
    
    
       <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    
    0 讨论(0)
  • 2021-01-26 16:20

    what happens if your device connected to internet, but no input data? You also have to check whether you are receiving data or not. Check below code to see you are connected internet and able access data. You just need to ping a site and see if your responce back is 200.

     public class internetchek extends AsyncTask<Void,Void,Void> {
    
     public boolean connection;
     Context ctx;
     public internetchek(Context context){
      this.ctx = context;
     }
     public internetchek(){
    
     }
    @Override
    protected void onPreExecute() {
    super.onPreExecute();
    }
    
    @Override
    protected Void doInBackground(Void... params) {
    
    if(isNetworkAvailable(this.ctx))
    {
    
     Log.d("NetworkAvailable","TRUE");
        if(connectGoogle())
        {
    
            Log.d("GooglePing","TRUE");
            connection=true;
        }
        else
        {
    
            Log.d("GooglePing","FALSE");
            connection=false;
        }
     }
     else {
    
        connection=false;
     }
    
    
     return null;
     }
    
     @Override
     protected void onPostExecute(Void aVoid) {
       super.onPostExecute(aVoid);
     }
    
     public static boolean isNetworkAvailable(Context context) {
       ConnectivityManager cm = (ConnectivityManager)        context.getSystemService(Context.CONNECTIVITY_SERVICE);
       NetworkInfo netInfo = cm.getActiveNetworkInfo();
       if (netInfo != null && netInfo.isConnected()) {
        return true;
       }
       return false;
      }
    
      public static boolean connectGoogle() {
        try {
         HttpURLConnection urlc = (HttpURLConnection) (new     URL("http://www.google.com").openConnection());
        urlc.setRequestProperty("User-Agent", "Test");
        urlc.setRequestProperty("Connection", "close");
        urlc.setConnectTimeout(10000);
        urlc.connect();
        return (urlc.getResponseCode() == 200);
    
      } catch (IOException e) {
    
         Log.d("GooglePing","IOEXCEPTION");
         e.printStackTrace();
         return false;
      }
    } 
    

    UPDATE: If you want to use it for other classes you can do this..make sure you put below code in AsyncTask or background running thread.

           if(internetchek.isNetworkAvailable(this.ctx)||internetchek.connectGoogle())
     {
    
     //Do your stuff here. when you have internet access 
    
     }
    
    0 讨论(0)
提交回复
热议问题