0

I have modified my previous code - this code is running properly. The only problem is that after launching it, on the first click it always shows an output as:

"Internet is not available"

But on the second click it shows the correct output.

public class MainActivity extends Activity {  

    boolean pingCheck;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button b1=(Button)findViewById(R.id.button1);

        b1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {                   
                Thread t = new Thread(new Runnable() {
                    public void run() {
                        pingCheck = isURLReachable(getApplicationContext());
                    }
                });

                t.start();

                if(pingCheck)
                {
                    Toast.makeText(MainActivity.this,"Network is available",Toast.LENGTH_LONG).show();
                }
                else
                {
                    Toast.makeText(MainActivity.this,"Network not available",Toast.LENGTH_LONG).show();
                }                   
            }
        });
    }


    static public boolean isURLReachable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();

        if (netInfo != null && netInfo.isConnected()) {
            try {
                URL url = new URL("http://google.com");   // Change to "http://google.com" for www  test.
                HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
                urlc.setConnectTimeout( 1000);          // 10 s.
                urlc.connect();

                if (urlc.getResponseCode() == 200) {        // 200 = "OK" code (http connection is fine).
                    Log.wtf("Connection", "Success !");
                    return true;
                } else {
                    return false;
                }
            } catch (MalformedURLException e1) {
                return false;
            } catch (IOException e) {
                return false;
            }
        }

        return false;
    }
}
krlzlx
  • 5,752
  • 14
  • 47
  • 55

1 Answers1

0

You cannot run an asynchronous task in a thread and check the result immediately after that. You need to wait for the task to complete. I suggest you pass in a callback to your ping check, and once the callback returns, run your code following if(pingCheck).

This should do the job:

public static interface OnInternetCheckCallback {
    void onInternetCheckResult(boolean available);
}

public static void hasInternetAccess(OnInternetCheckCallback callback) {
    new AsyncTask<OnInternetCheckCallback, Void, Boolean>() {
        private OnInternetCheckCallback mCallback;

        @Override
        protected Boolean doInBackground(OnInternetCheckCallback... params) {
            mCallback = params[0];
            try {
                URL checkUrl = new URL(HEALTHCHECK_URL);
                HttpURLConnection connection = (HttpURLConnection) checkUrl.openConnection();
                connection.setRequestProperty("User-Agent", "Android");
                connection.setRequestProperty("Connection", "close");
                connection.setConnectTimeout(1500);
                connection.connect();
                return (connection.getResponseCode() == 200 && connection.getContentLength() <= 0);
            } catch (IOException e) {
                Log.e(TAG, ".doInBackground() - Error checking internet connection", e);
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            mCallback.onInternetCheckResult(result);
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, callback);
}

Also, probably a better idea is to check against your own server rather than google.com as Google servers are blocked in some countries.

Sᴀᴍ Onᴇᴌᴀ
  • 8,218
  • 8
  • 36
  • 58
vkislicins
  • 3,331
  • 3
  • 32
  • 62
  • Is there something specific you didn't get? Have you now solved the problem? – vkislicins Nov 11 '16 at 17:23
  • @RahulGupta Maybe if you just used the solution I suggested you wouldn't experience the new problem? Also, don't check against google and don't use more than 1500-2000ms for timeout. Add properties - they might help. And if your call is taking a minute when your timeout is 1500ms, maybe your task doesn't get executed immediately? Maybe another `AsyncTask` is using up the thread? – vkislicins Nov 15 '16 at 19:39
  • ,thankx ,i just change url of google to other server and now all correct responses are in within 2s ,also keep timeout to 1500 – Rahul Gupta Nov 16 '16 at 15:42
  • @RahulGupta if you found my answer helpful, please pick it as the correct answer by ticking the box above. Thanks – vkislicins Nov 16 '16 at 16:48
  • Actually I used my code which I sent you a link, as you told that I should reduce timeout and URL to which we are pinging, so I did in that way only. I put url of my own website and reduce time out to 1500 . Thanks again you help me a lot – Rahul Gupta Nov 17 '16 at 12:18