public class MainActivity extends AppCompatActivity {
    Context context;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void show(View v){
        if (hasActiveInternetConnection(context)){
            Toast.makeText(MainActivity.this, "Internet connection available", Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(MainActivity.this, "Internet connection not available", Toast.LENGTH_SHORT).show();
        }
    }
    public boolean hasActiveInternetConnection(Context context) {
        if (isNetworkAvailable(context)) {
            new URLConnectTask().execute();
        } else {
           // Log.d(LOG_TAG, "No network available!");
            Toast.makeText(MainActivity.this, "No network available!", Toast.LENGTH_SHORT).show();
        }
        return false;
    }
    private class URLConnectTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {
            // params comes from the execute() call: params[0] is the url.
            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();
                String code = String.valueOf(urlc.getResponseCode() == 200);
                return code;
            } catch (IOException e) {
                //Log.e(LOG_TAG, "Error checking internet connection", e);
                //Toast.makeText(MainActivity.this, "Error checking internet connection", Toast.LENGTH_SHORT).show();
                return "Error checking internet connection";
            }
        }
    }
    private boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivityManager
                = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null;
    }
}
I used this post for internet connectivity check. But as they are not using asynctask, if I use this code I'm getting NetworkOnMainThreadException. I tried using asynctask but now I'm only getting message "Internet connection not available". I think its because the asynctask is not returning boolean value true. So any help would be much appreciated.
 
     
     
     
     
     
    