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.