Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ask user to connect to internet or quit app (android)

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.

like image 526
android question Avatar asked Sep 05 '14 12:09

android question


2 Answers

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();
like image 178
MobileMon Avatar answered Sep 22 '22 15:09

MobileMon


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;
}
like image 37
Anirudh Sharma Avatar answered Sep 18 '22 15:09

Anirudh Sharma