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
add permission in your manifest.xml
<uses-permission android:name="android.permission.INTERNET" />
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;
}
}
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());
}
}
}
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
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();
}
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;
}
}