15

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());
    }
  }
}
Hasib Mahmud
  • 806
  • 1
  • 10
  • 29
ZooZoo
  • 193
  • 1
  • 2
  • 11

15 Answers15

15
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"/>
vtuhtan
  • 1,056
  • 7
  • 18
  • thanks, i made changes. can u plz suggest where to put this method. i want to check this before main activity launched. – ZooZoo Apr 20 '12 at 08:27
  • `if (isOnline()==false) { YourActivity.this.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS)); }` – vtuhtan Apr 20 '12 at 09:07
7
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());
        }
    }
}
ozkanpakdil
  • 3,199
  • 31
  • 48
Sandeep
  • 2,573
  • 3
  • 21
  • 28
  • hi DeepSan. i applied above code. but still, it is not showing any alret n app dismiss :(.. its sucks . plz help – ZooZoo Apr 20 '12 at 10:05
  • is there any exception??? or if possible post the code, because all the methods in this thread are working fine, you please post your code... – Sandeep Apr 20 '12 at 11:24
  • thanks for code.. its not working on emulator but working perfectly on device :) – ZooZoo Apr 20 '12 at 11:29
7

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

Ishan Fernando
  • 2,758
  • 1
  • 31
  • 38
2

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" />
sampathpremarathna
  • 4,044
  • 5
  • 25
  • 37
1

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();
                }

            }
        };
Boe-Dev
  • 1,585
  • 2
  • 14
  • 26
1

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;
    }
}
  • hey can you provide more details, steps to take, what is different, and how this will help the person asking the question – kimcodes Oct 02 '20 at 13:41
0

add permission in your manifest.xml

 <uses-permission android:name="android.permission.INTERNET" />
Padma Kumar
  • 19,893
  • 17
  • 73
  • 130
0

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;
        }

} 
Dan Jurgen
  • 927
  • 1
  • 8
  • 13
0
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" />
IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198
user2914699
  • 265
  • 1
  • 3
  • 7
0
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();
    }
Sam
  • 104
  • 3
  • 10
0

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();
}
Mahesh Gawhane
  • 348
  • 3
  • 20
  • This only displays an alert, but the question also requires checking if an internet connection is available or not to know when to display the alert. – Marilia Mar 31 '16 at 19:21
  • thanks marilia.....i have edited my answer please check this....this may useful for you – Mahesh Gawhane Apr 05 '16 at 04:36
  • Although I can't test the solution right now, I'm glad you took the time to improve it and I see it now tries to address the connection availability. Cool! – Marilia Apr 06 '16 at 19:09
  • write hasConnection() and showNetDisabledAlertToUser() methods outside the onCreate() method and call this methods using if(){} else{} in onCreate() or button onClick(). Thank you. – Mahesh Gawhane Apr 07 '16 at 05:13
0

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();
}
Mahesh Gawhane
  • 348
  • 3
  • 20
  • AlertDialog.THEME_DEVICE_DEFAULT_LIGHT isn't working. it produces an error – JAMSHAID Dec 14 '19 at 01:58
  • @JAMSHAID use style to set theme. like – Mahesh Gawhane Feb 11 '20 at 12:00
0

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;
    }
}
0

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" />
Lakpriya Senevirathna
  • 2,488
  • 2
  • 17
  • 35
0

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();
    }
Kumar Santanu
  • 603
  • 1
  • 7
  • 14