如何发出连接等待警报



我制作的应用程序需要互联网访问。我希望它会显示带有两个按钮("重试"和"退出")的警报对话框。所以,我试试这个:

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

但是 AlertDialog 与 OnClickListener 异步工作,并且 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();
            }
        }   
    });

最新更新