Check Internet Android

Asked

Viewed 992 times

0

To check the internet connection I made the following method.

public class ChecaInternet extends AsyncTask<Void, Void, Boolean> {

@Override
protected Boolean doInBackground(Void... params) {
    boolean success = false;
    try {
        URL url = new URL("http://clients3.google.com/generate_204");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(1000);
        connection.connect();
        success = connection.getResponseCode() == 204 && connection.getContentLength() == 0;
    } catch (IOException e) {
        //e.printStackTrace();
        Log.e("IOEx", "Não Há Conexão!!!");
    }
    return success;
}

protected void onPostExecute(Boolean result) {
    Log.i("POST", "onPostExecute: "+result);
    super.onPostExecute(result);
}
}
  • In case some don’t know, I run this in an Asynctask because if it was run in the main thread you will receive a Networkonmainthread exception.

If I access the application without internet okay, it returns false. But if I access the application already connected and then turn off the wi-fi the method does not return false. It kind of hangs and returns nothing, I already debug and there is no error, it’s just as if the execution crashes and Asynctask is closed. Does anyone know the problem that is happening here?

I call this method as follows in an Activity:

public class TelaCadastroActivity extends AppCompatActivity {

    Button btnSave;

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

        btnSave = (Button) findViewById(R.id.btnCadastrar);

        btnSave.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                new ChecaInternet().execute();
                Toast.makeText(TelaCadastroActivity.this, "Tem conexão? ",          Toast.LENGTH_SHORT).show();
            }
        });

    }
}

2 answers

0

I have a wallpapers application in this application she needs to check the internet so the wallpapers download, maybe the method I made can help you out of a look:

private boolean haveNetworkConnection() {

boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;

for (NetworkInfo ni : ((ConnectivityManager) this.context.getSystemService("connectivity")).getAllNetworkInfo()) {
if (ni.getTypeName().equalsIgnoreCase("WIFI") && ni.isConnected()) {
haveConnectedWifi = true;
        }

if (ni.getTypeName().equalsIgnoreCase("MOBILE") && ni.isConnected()) {
haveConnectedMobile = true;
            }
        }
    if (haveConnectedWifi || haveConnectedMobile) {

    return true;
        }
    return false;

}

This method helps a lot here, it checks if there is any connection is wifi or mobile network, if it returns true, it downloads the wallpaper in the case of my application.

  • Rogers, I tested your solution and it works for some cases, for example, the function I put in the question it identifies if there is a connection and if it is working, so I saw your check if the connection is active. In my case I need something to check if it has connection and if it is working.

  • A while ago I looked for something similar but I couldn’t find it either or when I thought something didn’t work the right way, so I posted this. : / I hope you can solve, I will follow this topic.

  • I found the solution in another function, if you want I pass you already tested and works perfectly, but I really wanted to understand the problem of this, there are things that when others do work hahaha, check out this answer https://stackoverflow.com/questions/6493517/detect-if-android-device-has-internet-Connection/6493572#42018966

  • if possible pass there :)

  • https://stackoverflow.com/questions/6493517/detect-if-android-device-has-internet-connection/6493572#42018966

-1

public  boolean verificaConexao() {
        boolean conectado;
        ConnectivityManager conectivtyManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        if (conectivtyManager.getActiveNetworkInfo() != null
            && conectivtyManager.getActiveNetworkInfo().isAvailable()
            && conectivtyManager.getActiveNetworkInfo().isConnected()) {
        conectado = true;
        } else {
        conectado = false;
    }
return conectado;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.