I fetch JSON data through an AsyncTask in my activity like so:
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
// Load the plants via AsyncTask
new LoadItems().execute();
}
public class LoadItems extends AsyncTask<Void, Void, Boolean> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Boolean doInBackground(Void... arg0) {
updateJSONData();
return null;
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
updateList();
}
}
But before fetching data, I need to check the connectivity. So I created the following class, thanks to snippets of codes from others:
public class ConnectionCheck {
public static boolean isConnectionOnline() {
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;
}
// Dialog box for connection failure
public static void showConnectionFailureDialogBox(final Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(R.string.str_dialogBoxMessage);
builder.setPositiveButton(R.string.str_dialogBoxButton,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
((Activity) context).finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
And then I call those specially made functions like this:
@Override
protected void onPreExecute() {
super.onPreExecute();
if (!ConnectionCheck.isConnectionOnline()) {
ConnectionCheck.showConnectionFailureDialogBox(MyActivity.this);
this.cancel(true);
}
}
A dialog is supposed to show up when connection to the internet is non-existent. However, it pops up a dialog box every time. And when I checked the exit value I get, it's always 1. Never a 0. Is there something wrong with my code?
Also, it seems as if the code executes slowly? Is 'that' place the proper place to check the connection?
UPDATE This may be late but, the problem resides in the emulator I used. Nothing's really wrong with the code. I can't use the method suggested in the answer, as I do need a connection to the Internet. I'm restricting my app to not executing the statements if it doesn't have any network connection, 'cause it'll crash. I've read somewhere that following the method you guys were suggesting, the condition will return true even if there's no connection to the net; as long as the device is connected within a network. Or something along those lines.