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

后端 未结 5 1431
一整个雨季
一整个雨季 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: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 {
    
     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 
    
     }
    

提交回复
热议问题