To check the connection to the internet I did 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);
}
}
- If some do not know, I run this in an AsyncTask because if it was run on the main Thread you will get a NetworkOnMainThread exception.
If I access the internetless application okay, it returns false. But if I access the application already connected and then I disconnect the wi-fi method does not return false. It kind of crashes and does not return anything, I've debugged and there is no error, it's just as if execution crashed 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();
}
});
}
}