我制作需要互联网访问的应用程序。我希望它显示带有两个按钮的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异步工作和prepareConnection()的AlertDialog不会在连接Internet和用户单击“重试”之前等待。我认为我的问题在代码结构中。如何使它正确?

最佳答案

我用这样的东西

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

09-11 19:40
查看更多