Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display an alert when internet connection not available in android application

Tags:

android

alert

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());
    }
  }
}
like image 449
ZooZoo Avatar asked Apr 20 '12 07:04

ZooZoo


People also ask

How do you check internet is on or off in android programmatically?

In android, we can determine the internet connection status easily by using getActiveNetworkInfo() method of ConnectivityManager object. Following is the code snippet of using the ConnectivityManager class to know whether the internet connection is available or not.


1 Answers

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"/>
like image 192
vtuhtan Avatar answered Oct 16 '22 11:10

vtuhtan