ZooZoo
ZooZoo

Reputation: 193

Display an alert when internet connection not available in android application

In my application data comes from internet and I am trying to create a function that checks if a internet connection is available or not and if it isn't, it gives an alert messege that no internet connection available. i am using following code. but its not working.

public void onCreate(Bundle savedInstanceState){
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main1);
  if (isOnline())
  {
   // my code
  }
  else
  {
   Hotgames4meActivity1.this.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS)); 
    try {
       AlertDialog alertDialog = new AlertDialog.Builder(Hotgames4meActivity1.this).create();

       alertDialog.setTitle("Info");
       alertDialog.setMessage("Internet not available, Cross check your internet connectivity and try again");
       //alertDialog.setIcon(R.drawable.alerticon);
       alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int which) {
          finish();

         }
       });

       alertDialog.show();
    }
    catch(Exception e)
    {
       //Log.d(Constants.TAG, "Show Dialog: "+e.getMessage());
    }
  }
}

Upvotes: 15

Views: 88090

Answers (15)

Kumar Santanu
Kumar Santanu

Reputation: 701

2021-22 - Woking Code - No Internet with best practice

Create a class and extend with Application

     public class App extends Application {
    
        private static App instance;
    
        public static App getInstance() {
            return instance;
        }
    
        @Override
        public void onCreate() {
            super.onCreate();
            instance = this;
        }
    
        public static boolean isOnline() {
            ConnectivityManager connectivityManager = (ConnectivityManager) instance.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
            return activeNetworkInfo != null;
        }
}

In your AndroidManifest.xml

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <application
        android:name=".App"... // "name" add your app class inside application 
      Tag.

Now call in in your activity

if (App.isOnline()){
        //todo task
    }else{
        if (pBar != null && pBar.getVisibility() == View.VISIBLE) pBar.setVisibility(View.GONE);
        Toast.makeText(App.getInstance(), "No Internet", Toast.LENGTH_SHORT).show();
    }

Upvotes: 0

Lakpriya Senevirathna
Lakpriya Senevirathna

Reputation: 5109

If you want to show an alert when connection lost. You can use below method.

This method use to check connection one time. First you have to create this one in your class.

private boolean isNetworkConnected() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        if(!(cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected())){
            showNetworkDialog();
            return false;
        }
        return true;
    }

Create this method in your class as connection listener.

private void ConnectionCheck(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkRequest networkRequest = new NetworkRequest.Builder().build();
            connectivityManager.registerNetworkCallback(networkRequest, new ConnectivityManager.NetworkCallback() {
                @Override
                public void onAvailable(Network network) {
                    super.onAvailable(network);
                    Log.i("Tag", "active connection");
                }

                @Override
                public void onLost(Network network) {
                    super.onLost(network);
                    Log.i("Tag", "losing active connection");
                    isNetworkConnected();
                }
            });
        }
    }

For showing dialog, you may create showDialog() method. You can add 2 buttons. Re try and exit

private void showNetworkDialog(){
    new AlertDialog.Builder(MainActivity.this)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setTitle("Connection lost?")
            .setMessage("Please check your internet connection!")
            .setCancelable(false)
            .setPositiveButton("Exit", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            })
            .setNegativeButton("Retry", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    isNetworkConnected();
                }
            })
            .show();
}

Finally you can call this method in onCreate() method.

if(isNetworkConnected()){
            ConnectionCheck();
        }

in Manifest file you have to mention permission.

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Upvotes: 0

Mufaddal Shakir
Mufaddal Shakir

Reputation: 41

Just Try this I am using for my professional app

import androidx.appcompat.app.AlertDialog;

import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class MainActivity extends AppCompatActivity {    

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (isOnline()) {
             // Do you Stuff
        } else {
            try {
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("Error")
                        .setMessage("Internet not available, Cross check your internet connectivity and try again later...")
                        .setCancelable(false)
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .setNeutralButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        finish();

                    }
                }).show();
            } catch (Exception e) {
                Log.d(Constants.TAG, "Show Dialog: " + e.getMessage());
            }
        }
    }

    public boolean isOnline() {
        ConnectivityManager conMgr = (ConnectivityManager) getApplicationContext()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = conMgr.getActiveNetworkInfo();

        if(netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable()){
            return false;
        }
        return true;
    }
}

Upvotes: 1

Harshal Shende
Harshal Shende

Reputation: 1

This Code works fine If Intenet is available then starts app smoothly If not then pops a dialog asking to turn on or exit out of app

public void checkNetworkConnection(){
    AlertDialog.Builder builder =new AlertDialog.Builder(this);
    builder.setTitle("No internet Connection");
    builder.setMessage("Please turn on internet connection to continue!");
     builder.setPositiveButton("Turn On", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    MainActivity.this.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
                }
            }).show();

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

    AlertDialog alertDialog = builder.create();
    alertDialog.show();
}

public boolean isNetworkConnectionAvailable(){
    ConnectivityManager cm =
            (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null &&
            activeNetwork.isConnected();
    if(isConnected) {
        Log.d("Network", "Connected");
        return true;
    }
    else{
        checkNetworkConnection();
        Log.d("Network","Not Connected");
        return false;
    }
}

Upvotes: 0

Sandeep
Sandeep

Reputation: 2593

public void onCreate(Bundle obj) {
    super.onCreate(obj)
    setContextView(layout);

    if (isOnline()) {
        //do whatever you want to do 
    } else {
        try {
            AlertDialog alertDialog = new AlertDialog.Builder(con).create();

            alertDialog.setTitle("Info");
            alertDialog.setMessage("Internet not available, Cross check your internet connectivity and try again");
            alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
            alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    finish();

                }
            });

            alertDialog.show();
        } catch (Exception e) {
            Log.d(Constants.TAG, "Show Dialog: " + e.getMessage());
        }
    }
}

Upvotes: 7

Mahesh Gawhane
Mahesh Gawhane

Reputation: 338

write this code in your create method

if (internetConnection.hasConnection(BankAccount.this))
{
   // call your methods
}

else
{
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
    alertDialogBuilder
            .setMessage("No internet connection on your device. Would you like to enable it?")
            .setTitle("No Internet Connection")
            .setCancelable(false)
            .setPositiveButton(" Enable Internet ",
                    new DialogInterface.OnClickListener()
                    {

                        public void onClick(DialogInterface dialog, int id)
                        {
                            Intent dialogIntent = new Intent(android.provider.Settings.ACTION_SETTINGS);
                            dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            context.startActivity(dialogIntent);
                        }
                    });

    alertDialogBuilder.setNegativeButton(" Cancel ", new DialogInterface.OnClickListener()
    {
        public void onClick(DialogInterface dialog, int id)
        {
            dialog.cancel();
        }
    });

    AlertDialog alert = alertDialogBuilder.create();
    alert.show();
}

Upvotes: 0

Ishan Fernando
Ishan Fernando

Reputation: 2858

You can use these methods anywhere

public void checkNetworkConnection(){
    AlertDialog.Builder builder =new AlertDialog.Builder(this);
    builder.setTitle("No internet Connection");
    builder.setMessage("Please turn on internet connection to continue");
    builder.setNegativeButton("close", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
    AlertDialog alertDialog = builder.create();
    alertDialog.show();
}

public boolean isNetworkConnectionAvailable(){
    ConnectivityManager cm =
            (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null &&
            activeNetwork.isConnected();
    if(isConnected) {
        Log.d("Network", "Connected");
        return true;
        }
    else{
        checkNetworkConnection();
        Log.d("Network","Not Connected");
        return false;
    }
}

when you need to check connection available call isNetworkConnectionAvailable() method.If the network not available it will pop up your dialog box. If you need to check network in multiple screen add these methods to the super class and inherit that class to other class and call this method when need

Upvotes: 7

Mahesh Gawhane
Mahesh Gawhane

Reputation: 338

This is working in my code, try this:

@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (hasConnection(MainActivity.this)){
         //call methods
         //getJsonData();
      }
    else{
        showNetDisabledAlertToUser(MAinActivity.this);
    }
}

 public boolean hasConnection(Context context){
   ConnectivityManager cm=(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);             
    NetworkInfowifiNetwork=cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (wifiNetwork != null && wifiNetwork.isConnected()){
        return true;
    }          
   NetworkInfo mobileNetwork=cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    if (mobileNetwork != null && mobileNetwork.isConnected()){
        return true;
    }
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork != null && activeNetwork.isConnected()){
        return true;
    }
    return false;
}

public static void showNetDisabledAlertToUser(final Context context){
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context, AlertDialog.THEME_TRADITIONAL);
    alertDialogBuilder.setMessage("Would you like to enable it?")
            .setTitle("No Internet Connection")
            .setPositiveButton(" Enable Internet ", new DialogInterface.OnClickListener(){
                        public void onClick(DialogInterface dialog, int id){
                            Intent dialogIntent = new Intent(android.provider.Settings.ACTION_SETTINGS);                                   
                            dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            context.startActivity(dialogIntent);
                        }
                    });

                alertDialogBuilder.setNegativeButton(" Cancel ", new DialogInterface.OnClickListener(){
                public void onClick(DialogInterface dialog, int id){
                    dialog.cancel();
                }
            });
    AlertDialog alert = alertDialogBuilder.create();
    alert.show();
}

Upvotes: 0

user2914699
user2914699

Reputation: 265

public boolean isOnline() 
{


ConnectivityManager connectionManager;

if(app_context!=null)

connectionManager = (ConnectivityManager) app_context.getSystemService(Context.CONNECTIVITY_SERVICE);

        else
            return false;

        try 
        {
            if (connectionManager.getActiveNetworkInfo().isConnected()) 
            {
                Log.e(THIS_FILE, "Communicator ....isConnected()");
                return true;
            } 
            else
            { 
                Log.e(THIS_FILE, "Communicator ....isNotConnected()");
                return false;
            }
        } 
        catch (NullPointerException e) 
        {
            Log.e(THIS_FILE, "No Active Connection");
            return false;
        }
    }

set permission in manifest

<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Upvotes: 0

Sam
Sam

Reputation: 104

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager 
          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

if(!isNetworkAvailable()){
        //Toast.makeText(this, "No Internet Connection", Toast.LENGTH_SHORT).show();
        new AlertDialog.Builder(this)
        .setIcon(android.R.drawable.ic_dialog_alert)
        .setTitle("Closing the App")
        .setMessage("No Internet Connection,check your settings")
        .setPositiveButton("Close", new DialogInterface.OnClickListener()
    {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            finish();    
        }

    })
    .show();
    }

Upvotes: 0

Dan Jurgen
Dan Jurgen

Reputation: 927

The above method just informs you whether your mobile has the possibility to connect to the internet, however, it does not tell exactly if connectivity exists.. for example, you might be able to connect to a wifi, but be in a coffee shop where you should enter credentials into a hot spot website... or , your home wifi might be working, and you are connected to it, but cannot access internet. Use the below code to check for internet connetivity. it is preferable to use this inside an asynctask.

public boolean hasActiveInternetConnection()
{
        try
        {
            HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
            urlc.setRequestProperty("User-Agent", "Test");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(4000);
            urlc.setReadTimeout(4000);
            urlc.connect();
            networkcode2 = urlc.getResponseCode();
            return (urlc.getResponseCode() == 200);
        } catch (IOException e)
        {
            Log.i("warning", "Error checking internet connection", e);
            return false;
        }

} 

Upvotes: 0

Boe-Dev
Boe-Dev

Reputation: 1595

Maybe try this

handler.removeCallbacks(checkInternetConnection);
                handler.postDelayed(checkInternetConnection, UPDATE_INTERVAL); 



    public Runnable checkInternetConnection = new Runnable() {

            public void run() {

                handler.postDelayed(checkInternetConnection, UPDATE_INTERVAL);
                ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

                if(conMgr.getActiveNetworkInfo()!=null
                && conMgr.getActiveNetworkInfo().isAvailable()
                && conMgr.getActiveNetworkInfo().isConnected()){
                    alertOff();

                }
                else{
                    alertOn();
                }

            }
        };

Upvotes: 1

vtuhtan
vtuhtan

Reputation: 1066

public boolean isOnline() {
    ConnectivityManager conMgr = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = conMgr.getActiveNetworkInfo();

    if(netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable()){
        Toast.makeText(context, "No Internet connection!", Toast.LENGTH_LONG).show();
        return false;
    }
return true; 
}

And you must add premission for accessing network state and Internet:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Upvotes: 15

sampathpremarathna
sampathpremarathna

Reputation: 4064

try this

ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        android.net.NetworkInfo wifi = cm
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        android.net.NetworkInfo datac = cm
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        if ((wifi != null & datac != null)
                && (wifi.isConnected() | datac.isConnected())) {
                //connection is avlilable
                 }else{
                //no connection
                  Toast toast = Toast.makeText(context, "No Internet Connection",
                Toast.LENGTH_LONG);
        toast.show();  
                }

and don't forget to add following permssions

<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Upvotes: 2

Padma Kumar
Padma Kumar

Reputation: 20041

add permission in your manifest.xml

 <uses-permission android:name="android.permission.INTERNET" />

Upvotes: 0

Related Questions