Vay Vay -4 years ago 142
Java Question

Correct way to check internet connection with AsyncTask and output WebView content?

My app is based on a fullscreen

and I wanted to show a local file if there is no internet connection, otherwise load my website. I never used
before and tried the following:


protected void onCreate(Bundle savedInstanceState) {
// Check Internet Connection
mWebView = (WebView) findViewById(;
HostAvailabilityTask hostAvailable = new HostAvailabilityTask(this);
boolean online = hostAvailable.isOnline();

if (!online) {
// Loading local html file into web view
} else {
// load my website here


public class HostAvailabilityTask extends AsyncTask<String, Void, Boolean> {

private MainActivity main;

public HostAvailabilityTask(MainActivity main) {
this.main = main;

protected Boolean doInBackground(String... params) {
return isOnline(); // Correct way using AsyncTask?

protected void onPostExecute(Boolean... result) {
if(!result[0]) {
return; // What to return?

public boolean isOnline() {
Runtime runtime = Runtime.getRuntime();
try {
Process ipProcess = runtime.exec("/system/bin/ping -c 1");
int exitValue = ipProcess.waitFor();
return (exitValue == 0);
catch (IOException e) { e.printStackTrace(); }
catch (InterruptedException e) { e.printStackTrace(); }

return false;

As you can see I'm just calling the method
inside the
and think this is the wrong way to use a
? I just want to make sure to do it "the right way". I also don't know what would be logical to return in
in that case?

As stated before I never used
, so I hope someone could help me out. I also commented some lines in my code to make my confusion clear.

Answer Source
    public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error){
           //Your code to do
        Toast.makeText(getActivity(), "Your Internet Connection May not be active Or " + error , Toast.LENGTH_LONG).show();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download