如果没有互联网连接,我会弹出警报对话框。问题是UI每2秒刷新一次,每2秒弹出一个新对话框。有没有办法阻止这个?这是我的代码:
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();
}
}
在ErrorNotificationEvent中我得到了这个
@Subscribe
public void onErrorNotificationEvent(ErrorNotificationEvent event) {
setUI();
}
答案 0 :(得分:2)
创建对话框时应该保留对Dialog的引用,如果已经显示,则不要再显示它:
private AlertDialog _dialog;
public void setUI(){
if (!isNetworkAvailable() && (_dialog == null || !_dialog.isShowing())) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
...
_dialog = builder.show();
}
}
答案 1 :(得分:1)
您可以将一个计时器放入setUI调用中,以便在经过一定时间后它不会显示该对话框。
public long lastUIUpdate = 0;
@Subscribe
public void onErrorNotificationEvent(ErrorNotificationEvent event) {
if (System.currentTimeMillis() > lastUIUpdate + DateUtils.MINUTE_IN_MILLIS){
lastUIUpdate = System.currentTimeMillis();
setUI();
}
}