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();
}
});
}
}
Related: Test effective internet connection and How to implement a service that performs a method when identifying that there is an internet connection
– ramaral