我想在连接到互联网后立即关闭该对话框

时间:2017-07-22 12:48:13

标签: java android

这里我想显示两个对话框...一个用于是否有网络连接可用而另一个如果没有连接..但我希望当显示一个对话框时,另一个对话框应该被解除。 ...... dismiss()在这种情况下不工作....不知何故,如果我使用AlertDialog而不是AlertDialog.Builder来使用dismiss(),那么我无法给出setPositive,setNegative和setNeutral按钮.. ..非常感谢.......

BroadcastReceiver br;

@Override
protected void onCreate(Bundle savedInstanceState) {
   ...........//

    getStarted();
}
private void getStarted() {

    if (br == null) {

        br = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {

                ...............//

                if (state == NetworkInfo.State.CONNECTED) {

                    AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
                    builder1.setCancelable(false);
                    builder1.setTitle("Connected");
                    builder1.setMessage("Online");


                    builder1.setNeutralButton("Exit", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                           //
                        }
                    });

                    builder1.show();

                }

                else {

                    AlertDialog.Builder builder = new AlertDialog.Builder(context);
                    builder.setCancelable(false);
                    builder.setTitle("No Internet ");
                    builder.setMessage("Offline");


                    builder.setNeutralButton("Exit", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                    //
                        }
                    });

                    builder.show();
                }

            }

        };

        final IntentFilter if = new IntentFilter();
        if.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        getActivity().registerReceiver(br, if);
    }
}
}

2 个答案:

答案 0 :(得分:1)

如果已连接NetworkInfo.State.CONNECTED,则关闭您的对话框,请将builder1.show();更改为builder1.dismiss();

  if (state == NetworkInfo.State.CONNECTED) {

                        AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
                        builder1.setCancelable(false);
                        builder1.setTitle("Connected");
                        builder1.setMessage("Online");


                        builder1.setNeutralButton("Exit", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                               //
                            }
                        });

                        builder1.dismiss();

                    }

答案 1 :(得分:0)

使用广播接收器在使用意图过滤器android.net.ConnectivityManager.CONNECTIVITY_ACTION更改连接时作出反应。所以,当接收者接收到意图(或者连接被更改)时,你可以做你的事情。请参阅here