Search code examples
androidandroid-networkinginternet-connectionandroid-connectivitymanager

Check internet connection in android (not network connection)


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 . because each of them have some problems .

Method 1 check internet connection by pinging Google :

Runtime runtime = Runtime.getRuntime();
try {
       Process mIpAddressProcess = runtime.exec("/system/bin/ping -c 1   8.8.8.8");
       int mExitValue = mIpAddressProcess.waitFor();
       return mExitValue == 0;
} catch (InterruptedException | IOException ignore) {
            ignore.printStackTrace();
}

Method 2 check internet connection by ConnectivityManager :

public boolean checkNetwork() {

    ConnectivityManager internetManager = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = internetManager.getActiveNetworkInfo();
    return (networkInfo != null && networkInfo.isConnected() && networkInfo.isAvailable() && networkInfo.isConnectedOrConnecting());

}

I use method 1 inside an async task, but it doesn't work correctly sometimes and slow down the app, and Method 2 (ConnectivityManager) doesn't check internet connection , it checks only network connection !


Solution

  • 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);
    
    }