user3458008 user3458008 - 1 month ago 18
Android Question

How to perform AsyncTask for checking internet connection

I have the following code, all I need to do is to check if there is an internet connection or not..Since I'm getting a networkonmain thread exception, I 'm adviced to use async task. I want to perform network operation on hasActiveInternetConnection(Context context) and return true if connected to net else false . How do I do this using asynctask?

public class NetworkUtil extends AsyncTask<String, Void, String>{
Context context;

public NetworkUtil(Context context){
this.context = context;
}

private ProgressDialog dialog;

@Override
protected void onPreExecute() {

super.onPreExecute();
}

@Override
protected String doInBackground(String... arg0) {
if (new CheckNetwork(context).isNetworkAvailable())
{
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
boolean url= (urlc.getResponseCode() == 200);
String str = String.valueOf(url);
return str;
} catch (IOException e) {

}
}


// your get/post related code..like HttpPost = new HttpPost(url);
else {
Toast.makeText(context, "no internet!", Toast.LENGTH_SHORT).show();
}


return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}

Answer
There is no way to get an Internet connexion state, you will always have the network connection state.

But I found a pretty nice answer here: you send a request to google.com !! :) you can also try to ping to google by unix commandes if you want !!

here the guy is using a thread , and waiting a little bit for the answer, then returning a boolean . you do your staff in the handler . this is his code :

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

Then, I define the handler:

Handler h = new Handler() {
    @Override
    public void handleMessage(Message msg) {

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

        } else { // code if connected

        }   
    }
};

...and launch the test:

isNetworkAvailable(h,2000); // get the answser within 2000 ms
Comments