user3184395
user3184395

Reputation: 41

Android - Checking internet connection by pinging url

I am developing a social network app and most of the function required active connection. Sometime the phone is connected to WIFI, but the WIFI is not really internet accessible. The ordinary connectivitymanager does not secure that, it just check either the phone is connected or not. In order to do so, it has to setup a httpconnection in background by using asynctask.

public class checkConnectionStatus extends AsyncTask<Void, Void, HttpResponse>{
    private HttpGet httpGet;
    private HttpParams httpParameters;
    private DefaultHttpClient httpClient;
    private HttpResponse response;

    @Override
    protected void onPreExecute() { 
        String url = "http://www.google.come/";
        httpGet = new HttpGet(url);
        httpParameters = new BasicHttpParams();

        int timeoutConnection = 3000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);

        int timeoutSocket = 5000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
        httpClient = new DefaultHttpClient(httpParameters);

    }

    @Override
    protected Void doInBackground(Void... params) {
        try {

            response = httpClient.execute(httpGet);
            return response
        } catch (ClientProtocolException e) {
        } catch (IOException e) {
        }
        return null;
    }
    @Override
    protected void onPostExecute(HttpResponse result) {
        super.onPostExecute(result);
        // At here i do some thing
    }
}

I know that if this class in included in every single function class, it should be work well. But now, I want to reuse the code by simple calling new checkConnectionStatus().execute().

So whenever user trigger the action in onClick

onClick(){
if(checkConnectionStatus().execute() == false)

something like this.. is that possible to do so ? Network on main thread is another the issue.

Please help. Thanks

Upvotes: 0

Views: 796

Answers (2)

nasch
nasch

Reputation: 5498

Yes it's possible but you don't check the return value like that, instead pass in a callback and call to it in the AsyncTask's onPostExecute.

Upvotes: 0

Prabin Byanjankar
Prabin Byanjankar

Reputation: 267

I think this might help

ConnectivityManager cmgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        try {
            NetInfo[] netInfo = cmgr.getAllNetworkInfo();
            for (NetworkInfo ni : netInfo) {
                if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                    if (ni.isConnected())
                        return true;
                if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                    if (ni.isConnected())
                        return true;
            }
        } catch (Exception e) {
            e.getStackTrace();
        }
        return false;

Upvotes: 2

Related Questions