1

I am using the following code to show alert dialog to show no internet,

scenario 1: internet is off I open the activity it shows alert box no internet.

scenario 2(I have problem here): when I open the activity in presence of internet, and then i turn off my mobile data the alert not showing.

        ConnectivityManager connectivityManager = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

    //if there is no internet connection the dialog box created app will not work further
    if (networkInfo == null || !networkInfo.isConnected() || !networkInfo.isAvailable()) {
        Dialog networkdialog = new Dialog(this);
        networkdialog.setContentView(R.layout.networkalert);
        networkdialog.setCancelable(false);
        networkdialog.getWindow().setLayout(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
        networkdialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;

        Button retrybtn = networkdialog.findViewById(R.id.retrybtn);
        retrybtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //after click on retry the activity rerun
                recreate();
            }
        });
        networkdialog.show();
    }

I am using the above code in on create method of activity.

Zoe
  • 27,060
  • 21
  • 118
  • 148
  • The reason scene 2 doesn't work is coz the code works based on activity . In the scene 2 if you go to different activity and come back, then it will show the dialog. If you want to do this dynamically you need to have listener checking the internet continuously. Here are the links that may help you: [link1](https://stackoverflow.com/questions/25678216/android-internet-connectivity-change-listener) , [link2](https://stackoverflow.com/questions/15698790/broadcast-receiver-for-checking-internet-connection-in-android-app) – krish May 30 '21 at 13:18

0 Answers0