java - 如何设置连接等待提醒?

标签 java android android-alertdialog

我制作了需要互联网访问的应用程序。我希望它会显示带有两个按钮(“重试”和“退出”)的 AlertDialog。所以,我尝试这样做:

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;
}

但是带有 OnClickListener 的 AlertDialog 异步工作,并且在连接互联网和用户单击“重试”之前,prepareConnection() 不会等待。我认为我的问题出在代码结构上。怎样才能做到正确呢?

最佳答案

我用过这样的东西

boolean connection = checkNetworkConnection();
    if(!connection){
        createAlertDialog();
    }
    else{
        whenConnectionActive();
    }   

和createAlertDialog()函数

public void createAlertDialog(){    
    final Dialog dialog = new Dialog(this);
    dialog.setContentView(R.layout.custom_dialog);
    dialog.setTitle("Message");
    Button continueButton = (Button) dialog.findViewById(R.id.dialogContinueButton);
    TextView tw = (TextView) dialog.findViewById(R.id.dialogText);
    Button finishButton = (Button) dialog.findViewById(R.id.dialogFinishButton);

    tw.setText("Message");
    continueButton.setOnClickListener(new OnClickListener(){
        public void onClick(View v) {
            dialog.dismiss();
            boolean connection = checkNetworkConnection();
            if(!connection){
                dialog.show();
            }
            else{
               prepareConnection();
            }
        }   
    });

关于java - 如何设置连接等待提醒?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12893548/

相关文章:

java - QTP : How to add a Java list into my object repository

android - 如何通过此 Activity 修复此错误 : You need to use a Theme. AppCompat 主题(或后代)

android - 超过 EditText 限制时提醒用户

android - 如何自定义android AlertDialog文本属性

Java FileDialog 选择目录 : Mac OSX only?

java - Bukkit 交互式菜单 - 页面滚动

java - 在 playframework 中使用 @Lob 作为字段

android - onUpdate 的 appWidgetIds[] 中有哪些 ID?

android - 如何为 Galaxy S3 和 Nexus 7 创建不同的布局?

java - 意向服务单例