Android-Droid
Android-Droid

Reputation: 14565

Android check wifi connection

I have a specific question about wifi connection in Android.I'm working on a project which is downloading some data from web server and every time before starting the synchronization I'm checking about internet connection like this :

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

public static boolean chkNetworkStatus(Context context) {
    boolean result = false;
    new Thread() {
        @Override
        public void run() {


           for(int i=0;i<3;i++){
           HttpGet requestForTest = new HttpGet("http://m.google.com");
           try {
                  new DefaultHttpClient().execute(requestForTest);
                  responded = true;
                } catch (Exception e) {
                    responded = false;
                }
           }
        }
    }.start();
    boolean isOnline = isOnline(context);
    if(responded && isOnline){
        result = true;
    } else {
        result = false;
    }

    Log.e("","responded : "+responded);
    return result;
}

But in this situation when I'm still connected to wifi and i'm walking (loosing connection) and press sync button it's still returning true because I'm connected, but actually it's not doing anything.

Is there anyway that I can detect this or I should use connectionTimeOut function in HttpURLConnection class which I'm using?

Upvotes: 2

Views: 2324

Answers (2)

Vervatovskis
Vervatovskis

Reputation: 2367

try to do it like this:

public static void isNetworkAvailable(final Handler handler, final int timeout)
{

    // ask fo message '0' (not connected) or '1' (connected) on 'handler'
    // the answer must be send before before within the 'timeout' (in
    // milliseconds)

    new Thread()
    {

        private boolean responded = false;

        @Override
        public void run()
        {

            // set 'responded' to TRUE if is able to connect with google
            // mobile (responds fast)

            new Thread()
            {

                @Override
                public void run()
                {
                    HttpGet requestForTest = new HttpGet("http://m.google.com");
                    try
                    {
                        new DefaultHttpClient().execute(requestForTest); // can
                                                                            // last...
                        responded = true;
                    }
                    catch (Exception e)
                    {
                    }
                }

            }.start();

            try
            {
                int waited = 0;
                while (!responded && (waited < timeout))
                {
                    sleep(100);
                    if (!responded)
                    {
                        waited += 100;
                    }
                }
            }
            catch (InterruptedException e)
            {
            } // do nothing
            finally
            {
                if (!responded)
                {
                    handler.sendEmptyMessage(0);
                }
                else
                {
                    handler.sendEmptyMessage(1);
                }
            }

        }

    }.start();

}

Handler h = new Handler()
{

    @Override
    public void handleMessage(Message msg)
    {

        if (msg.what != 1)
        { // code if not connected


        }
        else
        { // code if connected


        }

    }
};

And in your Activity, call it like that:

 isNetworkAvailable(h, 2000);

Upvotes: 1

Vipul
Vipul

Reputation: 28093

Basically you will receive broadcast when network connectivity changes if you register.

android.net.conn.CONNECTIVITY_CHANGE

For Solution Here you go.

You will need to register for and handle BroadCastReceiver android.net.conn.CONNECTIVITY_CHANGE

Step 1

Include following permission in manifest

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Step2

Let Android know which class will be register for BroadCast Receiver.

<receiver android:name="ConnectivityReceiver_package_name.ConnectivityReceiver">
   <intent-filter>
      <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
   </intent-filter>
</receiver>

Step 3

Put your logic for various Network States.

public class ConnectivityReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

     String action = intent.getAction();

    boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,false);

     if(noConnectivity){

         //Show Warning Message
         //Take appropriate actions.
     }

    }

}

Upvotes: 1

Related Questions