如何使连接等待警报?

时间:2012-10-15 10:16:20

标签: 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()不会等待Internet连接,用户点击“重试”。我认为我的问题在于代码结构。怎么做对了?

1 个答案:

答案 0 :(得分:1)

我使用过这样的东西

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