Check internet connection in android (not network connection)

前端 未结 7 873
孤城傲影
孤城傲影 2020-12-20 03:44

I have a problem with checking internet connection in android at runtime. I use some different methods to check internet connection but i don\'t know which one is better . b

相关标签:
7条回答
  • 2020-12-20 03:59

    You can use below code to check whether network connection is available or not.

    public class NetworkConnection {
        public Context context;
    
        public NetworkConnection(Context applicationContext) {
            this.context=applicationContext;
        }
    
        public boolean isOnline() {
            ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getActiveNetworkInfo();
            if (netInfo != null && netInfo.isConnectedOrConnecting()) {
                return true;
            }
            return false;
        }
    }
    

    public class MainActivity extends AppCompatActivity {
        NetworkConnection nt_check;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            nt_check=new NetworkConnection(context);
            if(nt_check.isOnline()) {
                // do logic
            } else {
                // show message network is not available.
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-20 04:06

    To check if internet connection is available or not, you can use the below code snippet

        public static boolean hasActiveInternetConnection(Context context) {
        if (isNetworkAvailable(context)) {
            try {
                HttpURLConnection urlc = (HttpURLConnection) 
                        (new URL("http://clients3.google.com/generate_204")
                        .openConnection());
                urlc.setRequestProperty("User-Agent", "Android");
                urlc.setRequestProperty("Connection", "close");
                urlc.setConnectTimeout(1500); 
                urlc.connect();
                return (urlc.getResponseCode() == 204 && urlc.getContentLength() == 0);
            } catch (IOException e) {
                Log.e(LOG_TAG, "Error checking internet connection", e);
            }
        } else {
            Log.d(LOG_TAG, "No network available!");
        }
        return false;
    }
    

    This code snippet will also help you to identify whether you device is having internet connection even if you are connected through wifi network.

    Note: make sure to call this method in background thread ,because this can take time depending on your network speed, and should not be called in Main thread

    0 讨论(0)
  • 2020-12-20 04:08
    public static boolean isNetworkAvailable(Context context) {
        try {
            ConnectivityManager connManager = (ConnectivityManager) context.getSystemService
                    (Context.CONNECTIVITY_SERVICE);
            if (connManager.getActiveNetworkInfo() != null && connManager.getActiveNetworkInfo()
                    .isAvailable() && connManager.getActiveNetworkInfo().isConnected()) {
                return true;
            }
        } catch (Exception ex) {
    
            ex.printStackTrace();
            return false;
        }
        return false;
    }
    

    then just call this function from your fragment or Activity will work

    0 讨论(0)
  • 2020-12-20 04:13

    This is what i try in android to check internet connection it is not sleek solution but does the work given you have already checked for the network :

    try {
          HttpURLConnection urlConnection = (HttpURLConnection)
          (new URL("http://clients3.google.com/generate_204")
          .openConnection());
          urlConnection.setRequestProperty("User-Agent", "Android");
          urlConnection.setRequestProperty("Connection", "close");
          urlConnection.setConnectTimeout(1500);
          urlConnection.connect();
          if (urlConnection.getResponseCode() == 204 &&
          urlConnection.getContentLength() == 0) {
          Log.d("Network Checker", "Successfully connected to internet");
          return true;
          }
          } catch (IOException e) {
          Log.e("Network Checker", "Error checking internet connection", e);
          }
    

    It's accurate for me.Try and let me know if you find any other good solution.

    0 讨论(0)
  • 2020-12-20 04:20

    I'm using broadcast to check the connection every time. Create a class for connection info.

    import android.content.Context;
    import android.content.ContextWrapper;
    import android.net.ConnectivityManager;
    import android.net.NetworkInfo;
    
    
    public class ConnectivityStatus extends ContextWrapper{
    
        public ConnectivityStatus(Context base) {
            super(base);
        }
    
        public static boolean isConnected(Context context){
    
            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo connection = manager.getActiveNetworkInfo();
            if (connection != null && connection.isConnectedOrConnecting()){
                return true;
            }
            return false;
        }
    }
    

    Apply code into your Activity:

     private BroadcastReceiver receiver = new BroadcastReceiver() {
     @Override
     public void onReceive(Context context, Intent intent) {
            if(!ConnectivityStatus.isConnected(getContext())){
                // no connection
            }else {
                // connected
            }
        }
     };
    

    Register broadcast in your activity's onCreate() method:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_layout);
        your_activity_context.registerReceiver(receiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
        ..
        ...
        ....
      }
    

    Don't forget to unregistered/register on Activity cycle:

    @Override
    protected void onResume() {
        super.onResume();
        your_activity_context.registerReceiver(receiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        your_activity_context.unregisterReceiver(receiver);
    
    }
    
    0 讨论(0)
  • 2020-12-20 04:20

    Just check this LINK Here is the answer for both Connection & Internet.

    0 讨论(0)
提交回复
热议问题