0

I am have been fiddling with Android development and I have been having some trouble trying to check if there is an ACTIVE Internet connection even if the net is ON.

Since sometimes even though you are connected to the WIFI or DATA there are times there would be no connection.

Every time I click the button my app crashes. I am still a noob regarding boolean methods.

Thanks for any help in advance and if you guys think of any better ways I could approach this I would be grateful :D

This is my Mainactivity:

  @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

btnCheck = (Button) findViewById(R.id.btnCheck);

    btnCheck.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (isInternetAvailable()){
                Toast.makeText(MainActivity.this, "There is a connection", Toast.LENGTH_SHORT).show();
            }
            else{
                Toast.makeText(MainActivity.this, "NO connection", Toast.LENGTH_SHORT).show();
            }

        }
    });

}

public boolean isInternetAvailable() {
   try {
        int timeoutMs = 1500;
        Socket sock = new Socket();
        SocketAddress sockaddr = new InetSocketAddress("8.8.8.8", 80);

        sock.connect(sockaddr, timeoutMs);
        sock.close();

        return true;
    } catch (IOException e) { return false; }

}

1 Answers1

0

try below code

 Boolean isInternetPresent = false;
    ConnectionDetector cd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    btnCheck = (Button) findViewById(R.id.btnCheck);

    btnCheck.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            cd = new ConnectionDetector(getApplicationContext());
            isInternetPresent = cd.isConnectingToInternet();

            if (isInternetPresent) {

                Toast.makeText(MainActivity.this, "There is a connection", Toast.LENGTH_SHORT).show();

            }else {

              Toast.makeText(MainActivity.this, "NO connection", Toast.LENGTH_SHORT).show();

                }

            }
        });

    }

also don't forget to add internet permission in manifest file.

Omkar
  • 3,040
  • 1
  • 22
  • 42