简体   繁体   中英

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

My app is based on a fullscreen WebView and I wanted to show a local file if there is no internet connection, otherwise load my website. I never used AsyncTask before and tried the following:

MainActivity :

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // Check Internet Connection
    mWebView = (WebView) findViewById(R.id.activity_main_webview);
    HostAvailabilityTask hostAvailable = new HostAvailabilityTask(this);
    boolean online = hostAvailable.isOnline();

    if (!online) {
        // Loading local html file into web view
        mWebView.loadUrl("file:///android_asset/sample.html");
    } else {
        // load my website here

HostAvailabilityTask :

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 8.8.8.8");
            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 isOnline(); inside the MainActivity and think this is the wrong way to use a AsyncTask ? I just want to make sure to do it "the right way". I also don't know what would be logical to return in onPostExecute in that case?

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

 @Override
    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();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM