I wrote this code for checking INTERNET and it works but i have a problem that when wifi is on but internet does not exist!! in this situation my program force closed.
private class NetCheck extends AsyncTask<String,String,Boolean>
{
#Override
protected Boolean doInBackground(String... args){
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(1000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
when internet connected or disconnected its work but when wifi on and internet not exist its not work an application force close!
#Override
protected void onPostExecute(Boolean th){
if(th == true){
getcountHA();
}
else{
ShowAlertDialog();
}
}
}
whats problem!!
its my logcat
Check with this method:
public boolean isInternetAvailable() {
try {
InetAddress ipAddr = InetAddress.getByName("google.com"); //You can replace it with your name
if (ipAddr.equals("")) {
return false;
} else {
return true;
}
} catch (Exception e) {
return false;
}
}
Credits
my codes for check INTERNET are true and work great and the force close is because of another place. when INTERNET are not available the server give me some String codes like (
Related
My application activity is having a block of code which I want to check the connected network having active connection before accessing FireBase Auth Login.
I created a class for networkState add a block of code for checking networkActiveConnection
private void networkState() throws IOException {
final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
assert conMgr != null;
final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnectedOrConnecting()) {
Toast.makeText(getApplicationContext(),"Network connected",Toast.LENGTH_SHORT).show();
//checking active internet service
HttpURLConnection urlc = (HttpURLConnection)(new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(10000);
urlc.connect();
if(urlc.getResponseCode() == 200){
Toast.makeText(getApplicationContext(), "Network has active internet", Toast.LENGTH_SHORT).show();
//user login
signInUser();
}else {
Toast.makeText(getApplicationContext(), "No active internet connection", Toast.LENGTH_SHORT).show();
}
//end of checking active internet service
} else {
Toast.makeText(getApplicationContext(),"Network not connected",Toast.LENGTH_SHORT).show();
}
}
Application keeps crashing. I cant move without the solution.Where I missed? Is there any other method to check the connected network having active connection?
Finally I found an answer.Its actually happening due to the version. Up to Android 3.0 and above all long process activities will work at only AsyncTask
I restructured the actual internet connection in the device by load checking of Google.com. I don't know what it will happen when google.com is down.
The following code may help.
#SuppressLint("StaticFieldLeak")
public class activeConnection extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... params) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return false;
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
#Override
protected void onPostExecute(Boolean result) {
if (!result) { // code if not connected
AlertDialog.Builder builder = new AlertDialog.Builder(Customers.this, R.style.MyDialogTheme);
builder.setTitle("ALERT");
builder.setMessage("Activate your Internet connection and Try again");
builder.setCancelable(false);
builder.setPositiveButton(
"Retry",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
new activeConnection().execute();
}
});
AlertDialog alert11 = builder.create();
alert11.show();
} else { // code if connected
}
}
}
android my device connected with wifi but how to if wifi is connected but these is no internet connection
following is my code that i trying to check if no internet connection
public static boolean isConnectedWifi(Context context) {
NetworkInfo info=null;
if(context!=null){
info= IsNetConnectionAvailable.getNetworkInfo(context);
}
return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI);
}
it always return true when no internet access
NetworInfo.isAvailable and NetworkInfo.isConnected only indicate whether network connectivity is possible or existed, they can't indicate whether the connected situation has access to the public internet, long story short, they can't tell us the device is online indeed.
To check whether a device is online, try the following methods:
First:
#TargetApi(Build.VERSION_CODES.M)
public static boolean isNetworkOnline1(Context context) {
boolean isOnline = false;
try {
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkCapabilities capabilities = manager.getNetworkCapabilities(manager.getActiveNetwork()); // need ACCESS_NETWORK_STATE permission
isOnline = capabilities != null && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
} catch (Exception e) {
e.printStackTrace();
}
return isOnline;
}
Strength: 1. could run on UI thread; 2. fast and accurate.
Weakness: need API >= 23 and compatibility issues.
Second:
public static boolean isNetworkOnline2() {
boolean isOnline = false;
try {
Runtime runtime = Runtime.getRuntime();
Process p = runtime.exec("ping -c 1 8.8.8.8");
int waitFor = p.waitFor();
isOnline = waitFor == 0; // only when the waitFor value is zero, the network is online indeed
// BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
// String str;
// while ((str = br.readLine()) != null) {
// System.out.println(str); // you can get the ping detail info from Process.getInputStream()
// }
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return isOnline;
}
Strength: 1. could run on UI thread; 2. you can ping many times and do statistics for min/avg/max delayed time and packet loss rate.
Weakness: compatibility issues.
Third:
public static boolean isNetworkOnline3() {
boolean isOnline = false;
try {
URL url = new URL("http://www.google.com"); // or your server address
// URL url = new URL("http://www.baidu.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Connection", "close");
conn.setConnectTimeout(3000);
isOnline = conn.getResponseCode() == 200;
} catch (IOException e) {
e.printStackTrace();
}
return isOnline;
}
Strength: could use on all devices and APIs.
Weakness: time-consuming operation, can't run on UI thread.
Fourth:
public static boolean isNetworkOnline4() {
boolean isOnline = false;
try {
Socket socket = new Socket();
socket.connect(new InetSocketAddress("8.8.8.8", 53), 3000);
// socket.connect(new InetSocketAddress("114.114.114.114", 53), 3000);
isOnline = true;
} catch (IOException e) {
e.printStackTrace();
}
return isOnline;
}
Strength: 1. could use on all devices and APIs; 2. relatively fast and accurate.
Weakness: time-consuming operation, can't run on UI thread.
check with the below set of codes.
public boolean isNetworkAvailable(Context context) {
boolean isOnline = false;
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
NetworkCapabilities capabilities = manager.getNetworkCapabilities(manager.getActiveNetwork());
isOnline = capabilities != null && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
} else {
NetworkInfo activeNetworkInfo = manager.getActiveNetworkInfo();
isOnline = activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();
}
} catch (Exception e) {
e.printStackTrace();
}
return isOnline;
}
After searching for days and after trying various solutions, some are not perfect some are too LONG, below is a solution suggested by LEVIT using SOCKETS which is PERFECT to me. Any one searching on this solution may consult this post.
How to check internet access on Android? InetAddress never times out
Below is the portion of the code with example of task in AsyncTask
class InternetCheck extends AsyncTask<Void,Void,Boolean> {
private Consumer mConsumer;
public interface Consumer { void accept(Boolean internet); }
public InternetCheck(Consumer consumer) { mConsumer = consumer; execute(); }
#Override protected Boolean doInBackground(Void... voids) { try {
Socket sock = new Socket();
sock.connect(new InetSocketAddress("8.8.8.8", 53), 1500);
sock.close();
return true;
} catch (IOException e) { return false; } }
#Override protected void onPostExecute(Boolean internet) { mConsumer.accept(internet); }
}
///////////////////////////////////////////////////////////////////////////////////
// Usage
new InternetCheck(internet -> { /* do something with boolean response */ });
Below is a summary related to the solution
Possible Questions
Is it really fast enough?
Yes, very fast ;-)
Is there no reliable way to check internet, other than testing something on the internet?
Not as far as I know, but let me know, and I will edit my answer.
What if the DNS is down?
Google DNS (e.g. 8.8.8.8) is the largest public DNS in the world. As of 2013 it served 130 billion requests a day. Let 's just say, your app would probably not be the talk of the day.
Which permissions are required?
<uses-permission android:name="android.permission.INTERNET" />
The code you are using is just use to check if you are connected to wifi or not. It doesn't check if that wifi is slow or not. (No internet means slow connection).
I tried to use this code. Here, I try to hit google.com and have set a connection timeout value.
If here internet speed is good, then result returned is 200. So I check if the result code is 200 or not. If not, I show an alert that there is slow internet connection. Use it in an asyntask, and onPostExecute() check the value of returned result.
HttpURLConnection urlc = null;
try {
urlc = (HttpURLConnection) (new URL("http://www.google.com")
.openConnection());
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1000); // choose your own timeframe
urlc.setReadTimeout(2000); // choose your own timeframe
try {
urlc.connect();
// returning connection code.
return (urlc.getResponseCode());
} catch (IOException e1) {
e1.printStackTrace();
}
To just check if you are connected to the internet by Wi-Fi, have a look at the snippet below:
NetworkInfo getWifi(){
ConnectivityManager connManager = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
return mWifi;
}
Check whether it is connected or not by;
if(getWifi().isConnected()) {
//wi-fi connected
}
I'm trying to find the way to know when an user has Internet connection, since now I've got this method :
public boolean isNetworkOnline() {
boolean status=false;
try{
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getNetworkInfo(1);
if (netInfo != null && netInfo.getState()==NetworkInfo.State.CONNECTED) {
status= true;
}
}catch(Exception e){
e.printStackTrace();
return false;
}
return status;
}
This method returns true if user is CONNECTED but not if user has INTERNET CONNECTION, so I thought to if this method returns true, call another method to check if the user has connection to internet. For example someone can be connected to a router but without internet connection so I want to know when the user has internet connection or not.
I've read this answer and this other but all of them is returning me false when I've got Internet connection.... I thought that make a method that makes a ping to www.google.com it's a good approach to know if someone has internet connection so I tried to get this way but it didn't work for me...
Any idea or good approach (if it's better than my thoughts is better) to know when the user has internet connection?
The Simple Way To Check Internet Connectivity
public boolean isConnectingToInternet() {
if (networkConnectivity()) {
try {
Process p1 = Runtime.getRuntime().exec(
"ping -c 1 www.google.com");
int returnVal = p1.waitFor();
boolean reachable = (returnVal == 0);
if (reachable) {
System.out.println("Internet access");
return reachable;
} else {
return false;
}
} catch (Exception e) {
return false;
}
} else
return false;
}
private boolean networkConnectivity() {
ConnectivityManager cm = (ConnectivityManager) _context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
How To Call it
if (isConnectingToInternet()) {
// internet is connected and work properly...
}
else {
// something went wrong internet not working properly...
}
So simply copy and past the above two methods where you want to check the Internet connectivity. After that check the condition if (isConnectingToInternet()) { }
Can you try this method?
public boolean checkInternectConnection() {
try {
InetAddress inAddress= InetAddress.getByName("http://google.com");
if (inAddress.equals("")) {
return false;
} else {
return true;
}
} catch (Exception e) {
return false;
}
}
Please check this answer out and see if its helpful or not
You can try out this code
try {
URL url = new URL("http://"+params[0]);
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setRequestProperty("User-Agent", "Android Application:"+Z.APP_VERSION);
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1000 * 30); // mTimeout is in seconds
urlc.connect();
if (urlc.getResponseCode() == 200) {
Main.Log("getResponseCode == 200");
return new Boolean(true);
}
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
this is how i fixed this and i use it as a Utility method which can be called from any activity/fragment etc...:
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}//check if Wifi or Mobile data is enabled
private static class NetworkAsync extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... voids) {
try {
HttpURLConnection urlConnection = (HttpURLConnection)
(new URL("http://clients3.google.com/generate_204")
.openConnection());
urlConnection.setRequestProperty("User-Agent", "Android");
urlConnection.setRequestProperty("Connection", "close");
urlConnection.setConnectTimeout(1500);
urlConnection.connect();
return (urlConnection.getResponseCode() == 204 &&
urlConnection.getContentLength() == 0);
} catch (IOException e) {
// Error checking internet connection
}
return false;
}
}//network calls shouldn't be called from main thread otherwise it will throw //NetworkOnMainThreadException
and now you simply need to call this method from anywhere you want:
public static boolean checkInternetConnection(Context context) {
if (isNetworkAvailable(context)) {
try {
//used execute().get(); so that it gets awaited and returns the result
//after i receive a response
return new NetworkAsync().execute().get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return false;
}
I try to write an android program to check internet connection with two different methods. The first one is the most common method, CheckInternetConnection(), and the second method is through connecting to a website, ConnectGoogleTest().
The first one work perfectly, but in the second one my tablet hang! anybody knows why ?
The codes are:
public class myITClass {
private Context ctx ;
public myITClass(Context context){
this.ctx = context;
}
public boolean CheckInternetConnection() {
ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
//NetworkInfo ni = cm.getActiveNetworkInfo();
if (cm.getActiveNetworkInfo() == null) {
// There are no active networks.
return false;
} else {
return true;
}
}
public boolean googlePingTest(){
boolean res = false ;
try {
URL url = new URL("http://www.google.com/");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(15000);
urlc.connect();
if (urlc.getResponseCode() == 200) { res = true; }
} catch (MalformedURLException e1) {
res = false;
} catch (IOException e) {
res = false ;
}catch (Exception e){
res = false ;
}
return res;
}
}
You can send a ping to http://www.google.com/ through HttpURLConnection. Please make sure that you doing it in the background thread. Creating a network task must be run in the background. There are 3 options to do that:
Using AsyncTask
Using IntentService
Using Service
In this time, we will use AsyncTask. So create a private class inside your Activity:
private boolean res = false;
private class PingTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... urlSite) {
HttpURLConnection urlc = null;
try {
URL url = new URL("http://www.google.com/");
urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(15000);
urlc.setRequestMethod("GET");
urlc.connect();
if (urlc.getResponseCode() == 200) { res = true; }
} catch (MalformedURLException e1) {
res = false;
} catch (IOException e) {
res = false ;
}catch (Exception e){
res = false ;
}finally{
if (urlc != null) {
try{
// close the connection
urlc.disconnect();
}catch (Exception e){
e.printStackTrace();
}
}
}
return null;
}
}
Don't forget to add this field in your class:
private boolean res = false;
Create a method to get the status:
public boolean getStatus(){
return status;
}
How to use?
Execute the PingTask first to check the status:
PingTask ping = new PingTask();
ping.execute();
Get the status:
// if the connection is available
if(getStatus()==true){
// do your thing here.
}
The second method calls network synchronously on main thread, and that blocks the UI. Try using AsyncTask for it.
My app needs to check for internet access which I successfully implemented.
But I have a condition that internet is available but website it is trying to open is currently down.
In this case I need to show different message as an output.
How can I do so? Please give some idea.
public boolean isServerReachable()
// To check if server is reachable
{
try {
InetAddress.getByName("google.com").isReachable(3000); //Replace with your name
return true;
} catch (Exception e) {
return false;
}
}
You should check the status of the website's response Like this:
HttpResponse response = httpClient.execute(request);
int status = response.getStatusLine().getStatusCode();
and check here to find your status code.
then you can do your job by checking status code like this:
if (status == 200) // sucess
{
also I recommend you to use AsyncTask for your connection to do communication with server in background.
Try to catch NoHttpResponseException as follow
try{
//code to try to connect to your server
}catch(NoHttpResponseException ex){
//print stacktrace or display some message to say server is down
}
You can use this class. Make object and call methods.
public class ConnectionDetector {
private Context context;
public ConnectionDetector(Context context){
this.context = context;
}
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
public boolean isURLReachable() {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL(serverConnection.url); // Insert Url
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(10 * 1000); // 10 s.
urlc.connect();
if (urlc.getResponseCode() == 200) { // 200 = "OK" code (http connection is fine).
Log.wtf("Connection", "Success !");
return true;
} else {
return false;
}
} catch (MalformedURLException e1) {
return false;
} catch (IOException e) {
return false;
}
}
return false;
}
}