Search code examples
androidandroid-alertdialogandroid-wifi

Android :Display a dialog to enable wifi


I would like ,if the wifi is disabled , to display a dialog to the user ,that can decide if he wants to enable or disable the wifi.

Well i can see if the wifi is enabled or not, but how could i display that settings dialog.

This is the code i'm using :

if(wifiMan.isWifiEnabled()==false){
    Log.i("DEBUG","turning on wifi");
    wifiMan.setWifiEnabled(true);//I would like that the user decide
    }

  else {  
  Log.i("DEBUG","wifi is on");
   }

PS : i used : startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS)); but i'm getting this error : ACTION_WIFI_SETTINGS cannot be resolved or is not a field

I would like to have this interactive dialogue :

enter image description here


Solution

  • you can try this way if that is not working. The problem is may be you import wrong namespace. try this

    android.app.activity.startActivity(new android.content.Intent.Intent(android.provider.settings.Settings.ACTION_WIFI_SE‌​TTINGS));

    In case above does not work.you can also try with this

    startActivity(new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK));
    

    Create dialog like this :

    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                    context);
    
                // set title
                alertDialogBuilder.setTitle("Wifi Settings");
    
                // set dialog message
                alertDialogBuilder
                    .setMessage("Do you want to enable WIFI ?")
                    .setCancelable(false)
                    .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id) {
                            //enable wifi
                            wifiMan.setWifiEnabled(true);
                        }
                      })
                    .setNegativeButton("No",new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id) {
                            //disable wifi
                            wifiMan.setWifiEnabled(false);
                        }
                    });
    
                    // create alert dialog
                    AlertDialog alertDialog = alertDialogBuilder.create();
    
                    // show it
                    alertDialog.show();