I am trying to check if there is an active internet connection, and after searching, I found a working code answered by Levit:
https://stackoverflow.com/a/27312494/2920212
This seems to work fine except sometimes, it causes a lag where it appears like the app is frozen. I know its because the isOnline function is not run in a background thread. I have searched but unable to implement the background thread properly. Please find below the code:
public boolean isOnline() {
Runtime runtime = Runtime.getRuntime();
try {
Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int exitValue = ipProcess.waitFor();
return (exitValue == 0);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return false;
}
Here is what I've tried:
private void ChecOnline() {
class CheckURL extends AsyncTask<Void, Void, Boolean> {
@Override
protected Boolean doInBackground(Void... params) {
return isOnline();
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
String myresult = Boolean.toString(result);
Toast.makeText(getApplicationContext(), myresult, Toast.LENGTH_LONG).show();
}
}
CheckURL ucc = new CheckURL();
ucc.execute();
Nothing happens when ChecOnline(); is called.