Most of Android Applications use Internet Connection for Performing their Task .So here is Some code Snippet to Check whether the App is Connected to Internet Connection Or Not?
So lets Start :-
Step 1: First we Create a Utility Class fro Checking Internet Connection
ApplicationUtility.Java
public class ApplicationUtility {
ConnectivityManager connectivityManager;
NetworkInfo info;
public boolean checkConnection(Context context) {
boolean flag = false;
try {
connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
info = connectivityManager.getActiveNetworkInfo();
if (info.getType() == ConnectivityManager.TYPE_WIFI) {
System.out.println(info.getTypeName());
flag = true;
}
if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
System.out.println(info.getTypeName());
flag = true;
}
} catch (Exception exception) {
System.out.println("Exception at network connection....."
+ exception);
}
return flag;
}
}
Step 2:
Now we can use this Utility Class to Check Internet Connection from our Activity For Ex in Splash.Java we want to Check Internet Connection. If It return true than go to next Login Activity else Show Message to user that Internet Not Connected :
boolean checkConnection=new ApplicationUtility().checkConnection(this);
if (checkConnection) {
// start activity or do whatever you want
} else {
Toast.makeText(Splash.this, "connection not found...plz check connection", Toast.LENGTH_SHORT).show();
}
}
So using this you can Check the App is Connected to Internet or Not.
Comments
Post a Comment