I want to create URL monitor that will monitor in background each x seconds if the URL is online.
ConnectivityManager is not good for me because my app is used in controlled environment and although internet works some ports need to be closed.
So I need to monitor if foo.com/9000 is online all the time and when I request isOnline I want to get the result immediately, so monitoring should be done in background.
How would I accomplish this and is there a library that does this?
In Actionscript I would call UrlMonitor and pass it url
Could you use this to repeat the task:
Repeat a task with a time delay?
This being the task:
HttpGet request = new HttpGet();
URI uri = new URI("your_url");
request.setURI(uri);
HttpResponse response = httpClient.execute(request);
if (response.getStatusLine().toString().equalsIgnoreCase("HTTP/1.1 200 OK")) {
// it's there
}
private static boolean internetConnectionAvailable;
private static ScheduledExecutorService scheduleTaskExecutor;
public static void stopInternetMonitor() {
if (scheduleTaskExecutor != null && !scheduleTaskExecutor.isShutdown()) {
scheduleTaskExecutor.shutdown();
}
}
public static void startInternetMonitor() {
Runnable runnable = new Runnable() {
#Override
public void run() {
isInternetConnectionAvailableSync();
}
};
if (scheduleTaskExecutor != null) {
if (scheduleTaskExecutor.isShutdown()) {
scheduleTaskExecutor.scheduleWithFixedDelay(runnable, 0, 30, TimeUnit.SECONDS);
}
} else {
scheduleTaskExecutor = Executors.newScheduledThreadPool(5);
scheduleTaskExecutor.scheduleWithFixedDelay(runnable, 0, 30, TimeUnit.SECONDS);
}
}
public static boolean isInternetConnectionAvailableCached() {
ConnectivityManager cm = (ConnectivityManager) FashionTrenderApplication.getInstance()
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected() && internetConnectionAvailable) {
return true;
}
return false;
}
public static boolean isInternetConnectionAvailableSync() {
ConnectivityManager cm = (ConnectivityManager) FashionTrenderApplication.getInstance()
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
try {
URL url = new URL(EnvironmentConfiguration.getInstance().getServerUrl());
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setRequestProperty("User-Agent", "test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1000); // mTimeout is in seconds
urlc.connect();
if (urlc.getResponseCode() == 200) {
internetConnectionAvailable = true;
return true;
} else {
internetConnectionAvailable = false;
return false;
}
} catch (IOException e) {
Log.i("warning", "Error checking internet connection", e);
return false;
}
}
return false;
}
Related
I need a service in the background that constantly pings google. But I have no idea how to do it. I am new here. My method does not work does not repeat. It only works once and it always returns "false" .
isConnectedToServer function
public boolean isConnectedToServer(String url, int timeout) {
try{
URL myUrl = new URL(url);
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(timeout);
connection.connect();
return true;
} catch (Exception e) {
// Handle your exceptions
return false;
}}
onCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(isConnectedToServer("http://www.google.com",3000)){
Toast.makeText(this, "Okay", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "Not Okay", Toast.LENGTH_SHORT).show();
}}
Manifest
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
I see Not Okay once on the screen. Only once. Even when I have an internet connection. What can I do about it?
try this create a class that extends AsyncTask
public class CheckInternet extends AsyncTask<Void, Void, Boolean>{
private static final String TAG = "CheckInternet";
private Context context;
public CheckInternet(Context context) {
this.context = context;
}
#Override
protected Boolean doInBackground(Void... voids) {
Log.d(TAG, "doInBackground: ");
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
assert cm != null;
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnected();
if (isConnected) {
if ( executeCommand()) return true;
}
return false;
}
private boolean executeCommand(){
System.out.println("executeCommand");
Runtime runtime = Runtime.getRuntime();
try
{
Process mIpAddrProcess = runtime.exec("/system/bin/ping -c "+"www.google.com");
int mExitValue = mIpAddrProcess.waitFor();
System.out.println(" mExitValue "+mExitValue);
if(mExitValue==0){
return true;
}else{
return false;
}
}
catch (InterruptedException ignore)
{
ignore.printStackTrace();
System.out.println(" Exception:"+ignore);
}
catch (IOException e)
{
e.printStackTrace();
System.out.println(" Exception:"+e);
}
return false;
}
I have read this Answer About Getting Internet Connection Status in Android:
https://stackoverflow.com/a/22256277/4225644
But It doesn't work properly, for example if i have a network connection with no internet Access, this method takes too long time to return False:
public Boolean isOnline() {
try {
Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
int returnVal = p1.waitFor();
boolean reachable = (returnVal==0);
return reachable;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
How Can I decrease this Time to have a faster answer?
Use this code :
public static boolean isInternetConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null)
return false;
else {
if (ni.isConnected())
if (isOnline(context))
return true;
else
return false;
return false;
}
}
public static boolean isOnline(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.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(2000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return new Boolean(true);
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
You could check if there's connectivity with
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
That's for sure a faster way to determine if there's network acces instead of performing a request and waiting for a failure.
See docs as well.
this code may be help you if you want to check internet is present or not
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;
}
and give permission in your manifest.xml
<uses-permission android:name="android.permission.INTERNET" />
I am trying to write a part in my app that will differentiate between an Active Wifi connection and an actual connection to the internet. Finding out if there is an active Wifi connection is pretty simple using the connection manager however every time I try to test if I can connect to a website when the Wifi is connected but there is no internet connection I end up in an infinite loop.
I have tried to ping google however this ends up the same way:
Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
int returnVal = 5;
try {
returnVal = p1.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
boolean reachable = (returnVal==0);
return reachable;
I also tried this code:
if (InetAddress.getByName("www.xy.com").isReachable(timeout))
{ }
else
{ }
but I could not get isReachable to work.
It does works for me:
To verify network availability:
private Boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();
}
To verify internet access:
public Boolean isOnline() {
try {
Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
int returnVal = p1.waitFor();
boolean reachable = (returnVal==0);
return reachable;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
I use this:
public static void isNetworkAvailable(Context context){
HttpGet httpGet = new HttpGet("http://www.google.com");
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
try{
Log.d(TAG, "Checking network connection...");
httpClient.execute(httpGet);
Log.d(TAG, "Connection OK");
return;
}
catch(ClientProtocolException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
Log.d(TAG, "Connection unavailable");
}
It comes from an other stackoverflow answer but I can't find it.
EDIT:
Finally I found it: https://stackoverflow.com/a/1565243/2198638
Here is some modern code that uses an AsynTask to get around an issue where android crashes when you try and connect on the main thread and introduces an alert with a rinse and repeat option for the user.
class TestInternet 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;
}
#Override
protected void onPostExecute(Boolean result) {
if (!result) { // code if not connected
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("An internet connection is required.");
builder.setCancelable(false);
builder.setPositiveButton(
"TRY AGAIN",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
new TestInternet().execute();
}
});
AlertDialog alert11 = builder.create();
alert11.show();
} else { // code if connected
doMyStuff();
}
}
}
...
new TestInternet().execute();
To check if the android device is having an active connection, I use this hasActiveInternetConnection() method below that (1) tries to detect if network is available and (2) then connect to google.com to determine whether the network is active.
public static boolean hasActiveInternetConnection(Context context) {
if (isNetworkAvailable(context)) {
if (connectGoogle()) {
return true;
} else { //one more try
return connectGoogle();
}
} else {
log("No network available! (in hasActiveInternetConnection())");
return false;
}
}
public static boolean isNetworkAvailable(Context ct) {
ConnectivityManager connectivityManager = (ConnectivityManager) ct.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
public static boolean connectGoogle() {
try {
HttpURLConnection urlc = (HttpURLConnection)(new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(10000);
urlc.connect();
return (urlc.getResponseCode() == 200);
} catch (IOException e) {
log("IOException in connectGoogle())");
return false;
}
}
Query a website like this:
Make your class implement AsyncTaskCompleteListenere<Boolean> by adding the following method to your class:
#Override
public void onTaskComplete(Boolean result) {
Toast.makeText(getApplicationContext(), "URL Exist:" + result, Toast.LENGTH_LONG).show();
// continue your job
}
Add a simple testConnection method to your class to be called when you want to check for your connectivity:
public void testConnection() {
URLExistAsyncTask task = new URLExistAsyncTask(this);
String URL = "http://www.google.com";
task.execute(new String[]{URL});
}
And finally the URLExistAsyncTask class which perform the connectivity test as an asynchronous (background) task and calls back your onTaskComplete method once done:
public class URLExistAsyncTask extends AsyncTask<String, Void, Boolean> {
AsyncTaskCompleteListenere<Boolean> callback;
public URLExistAsyncTask(AsyncTaskCompleteListenere<Boolean> callback) {
this.callback = callback;
}
protected Boolean doInBackground(String... params) {
int code = 0;
try {
URL u = new URL(params[0]);
HttpURLConnection huc = (HttpURLConnection) u.openConnection();
huc.setRequestMethod("GET");
huc.connect();
code = huc.getResponseCode();
} catch (IOException e) {
return false;
} catch (Exception e) {
return false;
}
return code == 200;
}
protected void onPostExecute(Boolean result){
callback.onTaskComplete(result);
}
}
I did use this method. It worked for me! For people who want to get the real Internet!
public boolean isOnline() {
try {
HttpURLConnection httpURLConnection = (HttpURLConnection)(new URL("http://www.google.com").openConnection());
httpURLConnection.setRequestProperty("User-Agent", "Test");
httpURLConnection.setRequestProperty("Connection", "close");
httpURLConnection.setConnectTimeout(10000);
httpURLConnection.connect();
return (httpURLConnection.getResponseCode() == 200);
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
For doing this method every time! Just use a receiver
and =>
httpURLConnection.getResponseCode() == 200
This means the Internet is connected!
You can do it by create new parallel thread that count time :
final class QueryClass {
private int responseCode = -1;
private String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
if(url == null) {
return null;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(5000 );
urlConnection.setConnectTimeout(5000 );
Thread thread = new Thread() {
#Override
public void run() {
super.run();
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(responseCode == -1) {
//Perform error message
Intent intent = new Intent(context,ErrorsActivity.class);
intent.putExtra("errorTextMessage",R.string.errorNoInternet);
intent.putExtra("errorImage",R.drawable.no_wifi);
context.startActivity(intent);
}
}
};
thread.start();
urlConnection.connect();
responseCode = urlConnection.getResponseCode();
if (responseCode == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
}
i want to ask a question which may is very simple for some of you.
How can i figure out, whether my Application has an internet connection?
I want to connect to an MySQL Database and when there is no Internet, there should be an AlertDialog.
new AsyncTask() {
ProgressDialog dialog = ProgressDialog.show(AppActivity.this, "Lade", "Daten werden abgerufen...", true);
#Override
protected void onPostExecute(Object result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.dismiss();
max = Name.size()-1;
kontrolle = new boolean [max*2];
pb.setMax(max/2);
java.util.Arrays.fill(kontrolle, false);
bilder();
}
#Override
protected Object doInBackground(Object... arg0)
{
// TODO Auto-generated method stub
dialog.show();
getData();
return null;
}
}.execute();
private void getData()
{
String result = "";
ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
try
{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://.../read.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is=entity.getContent();
}
catch(Exception e)
{
Log.e("log-tag","Keine Verbindung"+e.toString());
Toast.makeText(getApplicationContext(), "Keine Verbindung!", Toast.LENGTH_SHORT).show();
}
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = "";
while((line= reader.readLine())!=null)
{
sb.append(line+"n");
}
is.close();
result = sb.toString();
result.trim();
}
catch(Exception e)
{
Log.e("log-tag","Error"+e.toString());
}
try
{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++)
{
JSONObject json_data = jArray.getJSONObject(i);
ID.add((String) json_data.get("id"));
Name.add((String) json_data.get("name"));
Pts.add((String)json_data.get("pts"));
}
}
catch(Exception e)
{
Log.e("log-tag","Error2"+e.toString());
}
}
How can i achieve that? i have no idea
i thought this
catch(Exception e)
{
Log.e("log-tag","Keine Verbindung"+e.toString());
Toast.makeText(getApplicationContext(), "Keine Verbindung!", Toast.LENGTH_SHORT).show();
}
would do the work, but when i have no connection (because i set my phone in flight mode) there is just an endless ProgressDialog :(
As Jon Taylor mentioned this is a duplicate question
you can use the following code to do this
this method checks whether mobile is connected to internet and returns true if connected and displays an alert box if not:
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) {
// There are no active networks.
AlertDialog.Builder altDialog= new AlertDialog.Builder(this);
altDialog.setMessage("No network connection!");
return false;
} else
return true;
}
add this to the manifest file,
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
EDIT: To get the network type you can use this code snippet:
ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
//mobile
State mobile = conMan.getNetworkInfo(0).getState();
//wifi
State wifi = conMan.getNetworkInfo(1).getState();
and then use it like that:
if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING) {
//mobile
} else if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING) {
//wifi
}
I followed this
http://www.helloandroid.com/tutorials/it-internet-connection-checker-snippet to check if there is internet connection on my android device.
The code block looks like this
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(1000 * 5); // Timeout is in seconds
urlc.connect();
if (urlc.getResponseCode() == 200) {
// http response is OK
Log.d("db", "Connection to " + url.toString() + " successful!");
return true;
}
However, my device is connected to open Wifi points which requires webpage log in before accessing the internet. This code seems to return true even without log in.
Was wondering what I can do?
If you have your own domain, create a web page that contains only one keyword of your choice.
For example: "success"
Now connect to that page instead of google and check if it returns "success".
URL url = new URL("http://www.yourdomain.com/yourpage.html");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(1000 * 5); // Timeout is in seconds
urlc.connect();
if (urlc.getResponseCode() == 200) {
// http response is OK
InputStream in = urlc.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = reader.readLine();
in.close();
if (line == "success"){
Log.d("db", "Connection to " + url.toString() + " successful!");
return true;
} else {
return false;
}
}
I think you have to use this method
to check internet connection i available.
public boolean isOnline()
{
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
boolean result = false;
if(ni != null )
{
if( ni.getState() == NetworkInfo.State.CONNECTED )
{
result = true;
}
}
return result;
}
private boolean checkInternetConnection() {
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
return true;
} else {
Toast toast = Toast
.makeText(
getApplicationContext(),
"No Internet Connection Found !!! Please Connect To Internet First",
Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(5000);
finish();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
return false;
}
}