Reputation: 2092
I've got an Alert Dialog popping up if there is no internet connection. The problem is the UI refreshes every 2 seconds and every 2 seconds a new dialog is popping up. Is there any way to stop this? here is my code:
public boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
public void setUI(){
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("No internet connection");
builder.setMessage("message ")
.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// intentionally do nothing;
}
})
.setNegativeButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog --> soft-close the app
finish();
}
});
if (!isNetworkAvailable()){
builder.show();
}
}
And in the ErrorNotificationEvent I got this
@Subscribe
public void onErrorNotificationEvent(ErrorNotificationEvent event) {
setUI();
}
Upvotes: 0
Views: 69
Reputation: 136
You can place a timer into the setUI call, so that it doesn't display the dialog until a certain amount of time has passed.
public long lastUIUpdate = 0;
@Subscribe
public void onErrorNotificationEvent(ErrorNotificationEvent event) {
if (System.currentTimeMillis() > lastUIUpdate + DateUtils.MINUTE_IN_MILLIS){
lastUIUpdate = System.currentTimeMillis();
setUI();
}
}
Upvotes: 1
Reputation: 5470
You should keep a reference to your Dialog when you create it, and do not show it again if it's already showing:
private AlertDialog _dialog;
public void setUI(){
if (!isNetworkAvailable() && (_dialog == null || !_dialog.isShowing())) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
...
_dialog = builder.show();
}
}
Upvotes: 2