Check network available in android - java

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

Related

Android how do I check internet connection

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

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.

Checking internet data receiving or not (Android) [duplicate]

This question already has answers here:
Detect network connection type on Android
(14 answers)
Closed 7 years ago.
I am using the following code for checking if internet connection available or not , this code works well if wifi or data disabled from mobile but problem is that this code hangs mobile when data is not receive during internet connected....
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;
}
}
<!--Constants.INTERNET_CONNECTION_URL="YOUR_WEB_SERVICE_URL/URL OF GOOGLE";-->
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import com.vgheater.util.Constants;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class CheckConnectivity {
private Context _context;
public CheckConnectivity(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 hasActiveInternetConnection() {
if (isConnectingToInternet()) {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL(Constants.INTERNET_CONNECTION_URL).openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(5000);
urlc.connect();
return (urlc.getResponseCode() == 200);
} catch (IOException e) {
return false;
}
} else {
return false;
}
}
}
You can use it as follows..
private class InternetTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog internetDialog = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
internetDialog = new ProgressDialog(RegisterUser.this);
internetDialog.setCancelable(false);
internetDialog.setCanceledOnTouchOutside(false);
internetDialog.setMessage(Html.fromHtml("<font color='#616161'>Checking Internet Connectivity.</font>"));
internetDialog.show();
}
protected Boolean doInBackground(String... urls) {
boolean response = false;
try {
response = checkConnectivity.hasActiveInternetConnection();
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
protected void onPostExecute(Boolean result) {
internetDialog.dismiss();
if (result) {
//do stuff
} else {
new ShowToast(RegisterUser.this, "Connect to Internet & Try Again !!");
}
}
}

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

Categories