0

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

4

1 回答 1

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();
            }
        }   
    });
于 2012-10-15T10:25:44.030 回答