Android how do I check internet connection - java

I want to be able to get a user internet connection. I have tried
boolean connected = false;
try {
ConnectivityManager cm = (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nInfo = cm.getActiveNetworkInfo();
connected = nInfo != null && nInfo.isAvailable() && nInfo.isConnected();
return connected;
} catch (Exception e) {
Log.e("Connectivity Exception", e.getMessage());
}
return connected;
But this only gets mobile data and wifi connection status, if the user has an expired data plan or doesn't even have any data plan I will not be able to know.
I want to know the internet status before making a server call instead of making a server and running in a runout time error.
Please help I have checked stack overflow, but I keep getting the same answer.

check internet coonnection with this function:
Boolean hasInternet(Context context) {
ConnectivityManager connectivityManager =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Network activeNetwork = connectivityManager.getActiveNetwork();
NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(activeNetwork);
if (capabilities != null) {
if (capabilities.hasCapability(NetworkCapabilities.TRANSPORT_WIFI)) return true;
else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) return true;
else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) return true;
else return false;
}
} else {
try {
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
} catch (NullPointerException e){
return false;
}
}
return false;
}

Related

Android - Check Internet Access

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" />

android internet connection avalability

After trying and searching on stackoverflow for ways to solve internet connection error on android, I found nothing what works for me. I tryed the code you can see at the bottom but it wont works for internet connection error. mWebView.loadUrl("file:///android_asset/myerrorpage.html"); become executed every time when the url in the browser isnt http://192./loc/index.php. When I have a redirecting at index.php the error file become showed. How can I change that, or know anyone a code that check the internet connection availability and then do something?
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
public boolean isInternetAvailable() {
try {
InetAddress ipAddr = InetAddress.getByName("google.com");
if (ipAddr.equals("")) {
return false;
mWebView.loadUrl("file:///android_asset/myerrorpage.html");
} else {
return true;
#Override
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_localy);
mWebView = (WebView) findViewById(R.id.webview);
// Brower niceties -- pinch / zoom, follow links in place
mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
mWebView.setWebViewClient(new GeoWebViewClient());
// Below required for geolocation
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setGeolocationEnabled(true);
mWebView.setWebChromeClient(new GeoWebChromeClient());
// Load google.com
mWebView.loadUrl("http://192./loc/index.php");
}
}
} catch (Exception e) {
return false;
}
}
Your question isn't very clear.
If you need check connection you need:
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
Then if need check for real internet connection you can try something like this:
public boolean isInternetAvailable() {
try {
InetAddress ipAddr = InetAddress.getByName("google.com");
if (ipAddr.equals("")) {
return false;
} else {
return true;
}
} catch (Exception e) {
return false;
}
}
And add the ACCESS_NETWORK_STATE permission to the manifest.

Monitor if URL is online constantly in Android

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;
}

How to check: LAN internet connection?

I have media console with LAN (cable) internet, my app is checking internet connection on the start, like this:
private boolean haveNetworkConnection() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo)
{
if (ni.getTypeName().equalsIgnoreCase("WIFI")) //WIFI
if (ni.isConnected()) haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE")) //EDGE
if (ni.isConnected()) haveConnectedMobile = true;
//LAN??
}
return haveConnectedWifi || haveConnectedMobile;
}
So, what should I add to my haveNetworkConnection() function to check LAN internet connection?
The official documentation states that the Type is TYPE_ETHERNET.

Check network available in android

I have to develop one android application.
Here i have to develop one twitter integration android application.
i have using below code:
public void onClickTwitt() {
if (isNetworkAvailable()) {
Twitt twitt = new Twitt(getActivity(), consumer_key, secret_key);
twitt.shareToTwitter(_Title);
} else {
showToast("No Network Connection Available !!!");
}
}
public boolean isNetworkAvailable() {
ConnectivityManager connectivity =(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
return false;
} else {
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;
}
Here am getting below error :
The method getSystemService(String) is undefined for the type
SubCate
Please help me...How can i resolve these error ????
public void onClickTwitt() {
if (isNetworkAvailable(this)) {
Twitt twitt = new Twitt(getActivity(), consumer_key, secret_key);
twitt.shareToTwitter(_Title);
} else {
showToast("No Network Connection Available !!!");
}
}
public boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity =(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
return false;
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
for (NetworkInfo networkInfo : info) {
if (networkInfo.getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
return false;
}
public static boolean isNetworkAvailable(Context context) {
if(context == null) { return false; }
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
// if no network is available networkInfo will be null, otherwise check if we are connected
try {
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
return true;
}
} catch (Exception e) {
AppLog.e(TAG, "isNetworkAvailable()" , e.getMessage());
}
return false;
}
and then do this
if(isNetworkAvailable(TempOrderActivity.this)) {
//do something
} else {
//do something
}
I use this Code and working great, Copied from my App. Hope this will solve your problem
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

Categories