Example usage for android.net NetworkInfo isConnected

List of usage examples for android.net NetworkInfo isConnected

Introduction

In this page you can find the example usage for android.net NetworkInfo isConnected.

Prototype

@Deprecated
public boolean isConnected() 

Source Link

Document

Indicates whether network connectivity exists and it is possible to establish connections and pass data.

Usage

From source file:jieehd.villain.updater.VillainUpdater.java

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"))
            if (ni.isConnected())
                haveConnectedWifi = true;
        if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
            if (ni.isConnected())
                haveConnectedMobile = true;

    }//  w w w  .j  ava 2s.co  m
    if (haveConnectedWifi == false && haveConnectedMobile == false) {
        Log.d("Network State", "false");
        AlertDialog.Builder alert = new AlertDialog.Builder(VillainUpdater.this);
        alert.setTitle("No Data Connection!");
        alert.setMessage(
                "You have no data connection, click ok to turn on WiFi or Mobile Data in order to check for OTA updates.");
        alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int whichButton) {
                // TODO Auto-generated method stub
                final Intent intent = new Intent(Intent.ACTION_MAIN, null);
                intent.addCategory(Intent.CATEGORY_LAUNCHER);
                final ComponentName cn = new ComponentName("com.android.settings",
                        "com.android.settings.wifi.WifiSettings");
                intent.setComponent(cn);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }

        });
        alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                return;
            }
        });
        alert.show();

    } else {
        download();
    }
    return haveConnectedWifi || haveConnectedMobile;
}

From source file:com.cricketkorner.cricket.VitamioListActivity.java

public boolean isNetworkAvailable() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getActiveNetworkInfo();
    // if no network is available networkInfo will be null
    // otherwise check if we are connected
    if (networkInfo != null && networkInfo.isConnected()) {
        return true;
    }/* w  w w  .jav  a 2  s  .c om*/
    return false;
}

From source file:com.yunzhi.tcpscclient.TcpChatService.java

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager = (ConnectivityManager) ctx
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

From source file:com.embeddedlog.LightUpDroid.LightUpPiSync.java

/**
 * Every request is handled by this method, which launches an async task to retrieve the data.
 * Before attempting to fetch the URL, makes sure that there is a network connection.
 *
 * @param uriBuilder The URI Builder of the JSON data address to request.
 * @param taskType Indicates which task it is to be performed.
 * @param alarmId If applicable, the Alarm ID (local, not LightUpPi Id) to perform the task.
 *//*from  w w w . j a v  a  2s. c om*/
private void getJsonHandler(Uri.Builder uriBuilder, TaskType taskType, long alarmId) {
    // First check if there is network connectivity
    ConnectivityManager connMgr = (ConnectivityManager) mActivityContext
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isConnected()) {
        String urlString = uriBuilder.build().toString();
        new DownloadJsonTask(taskType, alarmId).execute(urlString);
    } else {
        launchToast(R.string.lightuppi_no_connection);
    }
}

From source file:com.jacr.instagramtrendreader.Main.java

private boolean isOnline(int timeout) {
    // Test 1: Is GPRS / Wifi port ON?
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnected()) {
        try {//ww  w  .j a  v a 2 s  .com
            // Test 2: Ping specific url
            URL url = new URL("http://www.google.com");
            HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
            urlc.setConnectTimeout(timeout);
            urlc.connect();
            if (urlc.getResponseCode() == HttpURLConnection.HTTP_OK) {
                return true;
            }
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return false;
}

From source file:carsharing.starter.automotive.iot.ibm.com.mobilestarterapp.Home.CarBrowse.java

private void getAccurateLocation2(final GoogleMap googleMap) {
    final FragmentActivity activity = getActivity();
    if (activity == null) {
        return;//from w  ww.j a v  a  2  s.  com
    }
    final ConnectivityManager connectivityManager = (ConnectivityManager) activity
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
            && (networkInfo != null && networkInfo.isConnected())) {
        if (simulatedLocation == null) {
            if (ActivityCompat.checkSelfPermission(activity.getApplicationContext(),
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(activity.getApplicationContext(),
                            Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }

            locationManager = (LocationManager) activity.getApplicationContext()
                    .getSystemService(Context.LOCATION_SERVICE);

            final List<String> providers = locationManager.getProviders(true);
            Location finalLocation = null;

            for (String provider : providers) {
                if (ActivityCompat.checkSelfPermission(activity.getApplicationContext(),
                        Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                        && ActivityCompat.checkSelfPermission(activity.getApplicationContext(),
                                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    return;
                }

                final Location suggestedLocation = locationManager.getLastKnownLocation(provider);

                if (suggestedLocation == null) {
                    continue;
                }
                Log.i("Location Provider",
                        "provider=" + suggestedLocation.getProvider() + " time="
                                + new SimpleDateFormat("yyyy MMM dd HH:mm:ss")
                                        .format(suggestedLocation.getTime())
                                + " accuracy=" + suggestedLocation.getAccuracy() + " lat="
                                + suggestedLocation.getLatitude() + " lng=" + suggestedLocation.getLongitude());

                if (finalLocation == null) {
                    finalLocation = suggestedLocation;
                } else if (suggestedLocation.getTime() - finalLocation.getTime() > 1000) {
                    // drop more than 1000ms old data
                    finalLocation = suggestedLocation;
                } else if (suggestedLocation.getAccuracy() < finalLocation.getAccuracy()) {
                    // picks more acculate one
                    finalLocation = suggestedLocation;
                }
            }

            location = finalLocation;
        } else {
            location = simulatedLocation;
        }
        if (location != null) {
            final LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());

            mMap.addMarker(new MarkerOptions().position(userLocation).title("Your Location"));

            mMap.moveCamera(CameraUpdateFactory.newLatLng(userLocation));
            mMap.animateCamera(CameraUpdateFactory.zoomTo(14), 2000, null);

            getCars(location);
        } else {
            Log.e("Location Data", "Not Working!");

            //                Toast.makeText(getActivity().getApplicationContext(), "Please activate your location settings and restart the application!", Toast.LENGTH_LONG).show();
            getAccurateLocation(mMap);
        }
    } else {
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            Toast.makeText(activity.getApplicationContext(), "Please turn on your GPS", Toast.LENGTH_LONG)
                    .show();

            final Intent gpsIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivityForResult(gpsIntent, GPS_INTENT);

            if (networkInfo == null) {
                networkIntentNeeded = true;
            }
        } else {
            if (networkInfo == null) {
                Toast.makeText(activity.getApplicationContext(), "Please turn on Mobile Data or WIFI",
                        Toast.LENGTH_LONG).show();

                final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
                startActivityForResult(settingsIntent, SETTINGS_INTENT);
            }
        }
    }
}

From source file:org.devtcg.five.util.streaming.DownloadManager.java

public boolean isNetworkAvailable() {
    NetworkInfo info = mConnMan.getActiveNetworkInfo();
    if (info == null)
        return false;

    return info.isConnected();
}

From source file:org.loon.framework.android.game.LGameActivity.java

/**
 * ??/*from   w w w .j av a2s  .c  o  m*/
 * 
 * @return
 */
public boolean isNetwork() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();
    return (info != null && info.isConnected());
}

From source file:com.embeddedlog.LightUpDroid.LightUpPiSync.java

/**
 * Initiates a background thread to check if the LightUpPi server is reachable.
 *
 * @param guiHandler Handler for the activity GUI, for which to send one of the two runnables.
 * @param online Runnable to execute in the Handler if the server is online.
 * @param offline Runnable to execute in the Handler if the server is offline.
 *///w w w.  j av a  2  s  .co  m
public void startBackgroundServerCheck(final Handler guiHandler, final Runnable online,
        final Runnable offline) {
    // Check for network connectivity
    ConnectivityManager connMgr = (ConnectivityManager) mActivityContext
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    if ((networkInfo != null) && networkInfo.isConnected()
            && ((scheduleServerCheck == null) || scheduleServerCheck.isShutdown())) {
        // Get the ping address
        final Uri.Builder pingUri = getServerUriBuilder();
        pingUri.appendPath("ping");
        // Schedule the background server check
        scheduleServerCheck = Executors.newScheduledThreadPool(1);
        scheduleServerCheck.scheduleWithFixedDelay(new Runnable() {
            public void run() {
                int response = 0;
                try {
                    URL url = new URL(pingUri.build().toString());
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setReadTimeout(3000); /* milliseconds */
                    conn.setConnectTimeout(5000); /* milliseconds */
                    conn.setRequestMethod("GET");
                    conn.setDoInput(true);
                    conn.connect();
                    response = conn.getResponseCode();
                } catch (Exception e) {
                    // Safely ignored as a response!=200 will trigger the offline title
                }
                if (response == 200) {
                    if (Log.LOGV)
                        Log.i(LOG_TAG + "Server response 200");
                    guiHandler.post(online);
                } else {
                    if (Log.LOGV)
                        Log.i(LOG_TAG + "Server response NOT 200");
                    guiHandler.post(offline);
                }
            }
        }, 0, 30, TimeUnit.SECONDS);
        if (Log.LOGV)
            Log.v(LOG_TAG + "BackgroundServerCheck started");
    } else {
        if (Log.LOGV)
            Log.d(LOG_TAG + "Server response NOT 200");
        guiHandler.post(offline);
    }
}

From source file:ch.fixme.status.Main.java

private boolean checkNetwork() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo == null || !netInfo.isConnected()) {
        showError(getString(R.string.error_network_title), getString(R.string.error_network_msg));
        return false;
    }/*from w  ww  .  j  av  a  2  s  .c om*/
    return true;
}