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.
Related
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 (
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 have an app where i read some data from online api every 30sec. I have somewhat secured my app so that it will check if the device is connected to network and data can be trasfered.
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
But this does not include situations when i am connected to a network which needs authentification for internet access. Or when you have only local connectivity enabled.
The app tries to get data from that api and it crashes. Here is the request code:
public static JSONObject requestWebService(String serviceUrl) {
disableConnectionReuseIfNecessary();
HttpURLConnection urlConnection = null;
try {
// create connection
URL urlToRequest = new URL(serviceUrl);
urlConnection = (HttpURLConnection)urlToRequest.openConnection();
urlConnection.setConnectTimeout(10000);
urlConnection.setReadTimeout(10000);
// handle issues
int statusCode = urlConnection.getResponseCode();
if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
// handle unauthorized (if service requires user login)
} else if (statusCode != HttpURLConnection.HTTP_OK) {
// handle any other errors, like 404, 500,..
}
// create JSON object from content
InputStream in = new BufferedInputStream(
urlConnection.getInputStream());
return new JSONObject(getResponseText(in));
} catch (MalformedURLException e) {
// URL is invalid
} catch (SocketTimeoutException e) {
// data retrieval or connection timed out
} catch (IOException e) {
// could not read response body
// (could not create input stream)
} catch (JSONException e) {
// response body is no valid JSON string
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
All i need is that this app will not crash. How can i achieve this?
SOLUTION: it needed null check before reading JSON object... it was in different method:
public void check(){
JSONArray jsonArray = null;
if(isNetworkAvailable()) {
JSONObject dataZNetu = requestWebService("http://census.soe.com/get/ps2:v2/world_event?type=METAGAME");
if(dataZNetu != null) { //THIS WAS THE SOLUTION TO MY PROBLEM
try {
jsonArray = dataZNetu.getJSONArray("world_event_list");
for (int i = jsonArray.length() - 1; i >= 0; i--) {
JSONObject tempObj = jsonArray.getJSONObject(i);
int worldId = tempObj.getInt("world_id");
int stateID = tempObj.getInt("metagame_event_state");
int eventType = tempObj.getInt("metagame_event_id");
int instanceId = tempObj.getInt("instance_id");
checkUIchange(worldId, stateID, eventType, instanceId);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Since it looks like you are catching the appropriate exceptions, I'm guessing that the crash is in the code that calls this method.
If it tries to do something with the result, without checking for null, that's the problem.
But of course, knowing exactly where it crashes would help.
I want to check if the file exist on server and if exists set boolean value to true and use it's value out of the thread.
it's my code:
new Thread() {
public void run() {
try {
HttpURLConnection.setFollowRedirects(false);
// note : you may also need
//HttpURLConnection.setInstanceFollowRedirects(false)
HttpURLConnection con = (HttpURLConnection) new URL(URLName).openConnection();
con.setRequestMethod("HEAD");
if( (con.getResponseCode() == HttpURLConnection.HTTP_OK) ) {
fileExists = true;
}
else {
fileExists = false;
}
catch (Exception e) {
e.printStackTrace();
log.d("FILE_EXISTS", "false");;
}
}
}.start();
But the Boolean is false after passing this code and Im sure that file exists on the server!!