10

i am working on an image gallery app, in which application is retrieving images from internet.

so i want to prompt a dialog-box to ask user to connect to internet or quit application.

show user both WiFi and Carrier network option.

android question
  • 137
  • 2
  • 10
  • As simple as it is, just check if there's an active network connection. If not, show a yes|no Dialog. If positive, then show the Network settings. Else, finish the activity. – Phantômaxx Sep 05 '14 at 12:21

5 Answers5

6

this checks for both wifi and mobile data..run tis code on splash or your main activity to check network connection.popup the dialog if the net is not connected and finish the activity.It's that simple

private boolean haveNetworkConnection() {
    boolean haveConnectedWifi = false;
    boolean haveConnectedMobile = false;

    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo[] netInfo = cm.getAllNetworkInfo();
    for (NetworkInfo ni : netInfo) {
        if (ni.getTypeName().equalsIgnoreCase("WIFI"))
            if (ni.isConnected())
                haveConnectedWifi = true;
        if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
            if (ni.isConnected())
                haveConnectedMobile = true;
    }
    return haveConnectedWifi || haveConnectedMobile;
}
Anirudh Sharma
  • 7,968
  • 13
  • 40
  • 42
  • What if I want to check for internet connection in each fragment (in other words, in each UI page). Lets say first I click image and I see the big image, but now if the internet connection is lost, I should notify user. Where to place this code, so that I check for internet connectivity in all screens? – sofs1 Oct 07 '16 at 07:42
  • 1
    create a common util class and access it from there.Also you can create a broadcast and listen to network change wherever you want. – Anirudh Sharma Oct 07 '16 at 08:45
5

Try this:

public static boolean isConnected(Context context){
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mobileInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

if ((wifiInfo != null && wifiInfo.isConnected()) || (mobileInfo != null && mobileInfo.isConnected())) {
        return true;
}else{
        showDialog();
         return false;
}

private void showDialog()
{
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Connect to wifi or quit")
        .setCancelable(false)
        .setPositiveButton("Connect to WIFI", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
                startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
           }
         })
        .setNegativeButton("Quit", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
                this.finish();
           }
        });
         AlertDialog alert = builder.create();
         alert.show();
}
Sagar Pilkhwal
  • 3,998
  • 2
  • 25
  • 77
  • well extremely sorry for that, but my code also checks if there is any internet connection which is required as per the scenario. – Sagar Pilkhwal Sep 05 '14 at 16:41
3

First you should check if they are already connected or not (tons of examples how to do this online)

If not, then use this code

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Connect to wifi or quit")
.setCancelable(false)
.setPositiveButton("Connect to WIFI", new DialogInterface.OnClickListener() {
   public void onClick(DialogInterface dialog, int id) {
        startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
   }
 })
.setNegativeButton("Quit", new DialogInterface.OnClickListener() {
   public void onClick(DialogInterface dialog, int id) {
        this.finish();
   }
});
 AlertDialog alert = builder.create();
 alert.show();
MobileMon
  • 8,341
  • 5
  • 56
  • 75
1
//Checking For Internet Connection
ConnectionDetector cd = new ConnectionDetector(getApplicationContext()); 

    // Check if Internet present
    if (!cd.isConnectingToInternet()) {
        // Internet Connection is not present
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Connect to wifi or quit")
       .setCancelable(false)
       .setPositiveButton("Connect to WIFI", new DialogInterface.OnClickListener() {

               public void onClick(DialogInterface dialog, int id) {
                   startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
               }
        })
      .setNegativeButton("Quit", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
               this.finish();
         }
      });
      AlertDialog alert = builder.create();
      alert.show();

    return;
    }
Pragnesh Ghoda シ
  • 8,318
  • 3
  • 25
  • 40
0

This is the way it is done.

This class checks for a valid internet connection:

public class ConnectionStatus {

    private Context _context;

    public ConnectionStatus(Context context) {
        this._context = context;
    }

    public boolean isConnectionAvailable() {
        ConnectivityManager connectivity = (ConnectivityManager) _context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null)
                for (int i = 0; i < info.length; i++)
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
        }
        return false;
    }
}

The following method opens the wi-fi panel if there is no valid internet connection:

public void addListenerOnWifiButton() {
        Button btnWifi = (Button)findViewById(R.id.btnWifi);

        iia = new ConnectionStatus(getApplicationContext());

        isConnected = iia.isConnectionAvailable();
        if (!isConnected) {
            btnWifi.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
                    Toast.makeText(getBaseContext(), "Please connect to a hotspot",
                            Toast.LENGTH_SHORT).show();
                }
            });
        }
        else {
            btnWifi.setVisibility(4);
            warning.setText("This app may use your mobile data to update events and get their details.");
        }
    }

The following method opens the 3G panel if there is no valid internet connection:

public void addListenerOn3GButton() {
    Button btnThreeGee = (Button)findViewById(R.id.btn3G);
    iia = new ConnectionStatus(getApplicationContext());

    isConnected = iia.isConnectionAvailable();
    if (!isConnected) {
        btnThreeGee.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            startActivity(new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS));
            Toast.makeText(getBaseContext(), "Please check 'Data enabled' option",
                    Toast.LENGTH_SHORT).show();
        }
    });
    }
    else {

         btnThreeGee.setVisibility(4);
         cont.setVisibility(View.VISIBLE);
         warning.setText("This app may use your mobile data to update events and get their details.");
        }
}

Hope this helps :)

Michele La Ferla
  • 6,775
  • 11
  • 53
  • 79
  • 1
    Hey man, would you have an idea on how to open the data roaming settings prompt as a dialog type enable/disable similar to that of Bluetooth/GPS prompt? Your answer works fine but it opens a new activity instead of just a small dialog which impairs the user experience. – Razgriz Apr 27 '16 at 13:07
  • I think [this](http://stackoverflow.com/a/15456565/1116216) answer will help you achieve what you need. – Michele La Ferla Apr 27 '16 at 13:37
  • 1
    What I meant was that a dialog box will appear and clicking Ok/Yes/etc will automatically turn the Mobile Data on. Similar to how you get prompted to turn on Bluetooth with a dialog box and if you click yes, your bluetooth will automatically turn on. Or how opening google maps shows that "Allow this app to use your location?" and clicking yes will enable your location settings. Not click yes and get shown a new activity. – Razgriz Apr 27 '16 at 13:49
  • I am not sure Google actually allow that, as a security feature. The devs at Mountain View were concerned that turning on data 'easily' can be done by mistake and incur unneccessary tariffs on the user. So they made sure to take the users to a differnet screen to turn on data. You can always use the back button to return back to the app after switching on 3G. – Michele La Ferla Apr 27 '16 at 13:57