I make the application which need internet access. And I want that it will showing AlertDialog with two buttons (“Retry” and “Quit”). So, I try this:
void prepareConnection() {
if(!checkInternetConnection()) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setMessage(R.string.internet_not_available);
alert.setTitle(R.string.app_name);
alert.setPositiveButton(R.string.retry, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
prepareConnection();
}});
alert.setNegativeButton(R.string.quit, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}});
alert.show();
}
}
boolean checkInternetConnection() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if ((cm.getActiveNetworkInfo() != null) && cm.getActiveNetworkInfo().isAvailable() && cm.getActiveNetworkInfo().isConnected()) {
return true;
}
return false;
}
But AlertDialog with OnClickListener working asynchronously and prepareConnection() doesn’t wait before Internet will be connected and user click “Retry”. I think my problem in a code structure. How to make it right?
I used something like this
and createAlertDialog() function