Example usage for android.net NetworkInfo isConnectedOrConnecting

List of usage examples for android.net NetworkInfo isConnectedOrConnecting

Introduction

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

Prototype

@Deprecated
public boolean isConnectedOrConnecting() 

Source Link

Document

Indicates whether network connectivity exists or is in the process of being established.

Usage

From source file:org.xbmc.kore.ui.hosts.AddHostFragmentZeroconf.java

private boolean isNetworkConnected() {
    ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}

From source file:com.sitexa.android.data.net.volley.VolleyApi.java

private boolean isThereInternetConnection() {
    ConnectivityManager connectivityManager = (ConnectivityManager) this.context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
    return (networkInfo != null && networkInfo.isConnectedOrConnecting());
}

From source file:it.uniroma2.foundme.studente.Connection.java

@Override
protected String[] doInBackground(String... params) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    if (!isConnected)
        return new String[] { Variables_it.NO_INTERNET };

    if (toDo.equalsIgnoreCase(Variables_it.REGIS)) {
        String regid = RegistrationActivity.GoogleCloudRegistration();
        if (regid == null)
            return new String[] { Variables_it.FAILED_GCM };
        else//from w w w  .j  a v a  2  s.co m
            params[10] = regid;
    }
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    for (int i = 1; i < params.length; i = i + 2) {
        nameValuePairs.add(new BasicNameValuePair(params[i], params[i + 1]));
    }
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(params[0]);
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
    } catch (Exception e) {
        return new String[] { Variables_it.INVALID_IP };
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, Variables_it.ISO), 8);
        StringBuilder sb = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();
    } catch (Exception e) {
        return new String[] { Variables_it.FAIL_CONNECTION };
    }
    try {
        if (toDo.equalsIgnoreCase(Variables_it.GET) && returnMessage.equalsIgnoreCase(Variables_it.MID)) {
            json_data = new JSONObject(result.substring(result.indexOf("{"), result.lastIndexOf("}") + 1));
            String[] received = new String[2];
            received[0] = json_data.getString(Variables_it.MSG);
            received[1] = json_data.getString(Variables_it.VIS);
            return received;
        } else if (toDo.equalsIgnoreCase(Variables_it.GET)
                && !returnMessage.equalsIgnoreCase(Variables_it.MID)) {
            json_data = new JSONObject(result);
            List<String> list = new ArrayList<String>();
            for (int i = 0;; i++) {
                try {
                    String n = json_data.getString(Integer.toString(i + 1));
                    list.add(n);
                } catch (JSONException e) {
                    break;
                }
            }
            String[] received = new String[list.size()];
            list.toArray(received);
            return received;
        } else if (returnMessage.equalsIgnoreCase(Variables_it.GET_INFO_OK)) {
            json_data = new JSONObject(result.substring(result.indexOf("{"), result.lastIndexOf("}") + 1));
            return new String[] { returnMessage };
        } else if (returnMessage.equalsIgnoreCase(Variables_it.NAME)) {
            json_data = new JSONObject(result.substring(result.indexOf("{"), result.lastIndexOf("}") + 1));
            return new String[] { json_data.getString(Variables_it.NAME), json_data.getString(Variables_it.ID),
                    json_data.getString(Variables_it.GCMKEY) };
        } else {
            json_data = new JSONObject(result.substring(result.indexOf("{"), result.lastIndexOf("}") + 1));
            code = (json_data.getInt(Variables_it.CODE));
        }
        if (returnMessage.equalsIgnoreCase(Variables_it.ADD_COURSE_OK) && code == 2) {
            return new String[] { Variables_it.ALREDY_FOLLOWING };
        }
        if (code == 1) {
            return new String[] { returnMessage };
        } else {

            return new String[] { Variables_it.ERROR };
        }
    } catch (Exception e) {
        if (returnMessage.equalsIgnoreCase(Variables_it.NAME)) {
            return new String[] { Variables_it.ERROR };
        } else if (toDo.equalsIgnoreCase(Variables_it.GET)
                && !returnMessage.equalsIgnoreCase(Variables_it.MSG)) {
            return new String[] { Variables_it.NO_COURSE };
        } else if (toDo.equalsIgnoreCase(Variables_it.GET)
                && returnMessage.equalsIgnoreCase(Variables_it.MSG)) {
            return new String[] { Variables_it.NO_MSG };
        }
        return new String[] { Variables_it.JSON_FAILURE };
    }
}

From source file:com.radioactiveyak.location_best_practices.services.PlaceCheckinService.java

/**
 * {@inheritDoc}//from w  w w.java 2 s. c  om
 * Perform a checkin the specified venue. If the checkin fails, add it to the queue and
 * set an alarm to retry.
 * 
 * Query the checkin queue to see if there are pending checkins to be retried.
 */
@Override
protected void onHandleIntent(Intent intent) {
    // Retrieve the details for the checkin to perform.
    String reference = intent.getStringExtra(PlacesConstants.EXTRA_KEY_REFERENCE);
    String id = intent.getStringExtra(PlacesConstants.EXTRA_KEY_ID);
    long timeStamp = intent.getLongExtra(PlacesConstants.EXTRA_KEY_TIME_STAMP, 0);

    // Check if we're running in the foreground, if not, check if
    // we have permission to do background updates.
    boolean backgroundAllowed = cm.getBackgroundDataSetting();
    boolean inBackground = sharedPreferences.getBoolean(PlacesConstants.EXTRA_KEY_IN_BACKGROUND, true);

    if (reference != null && !backgroundAllowed && inBackground) {
        addToQueue(timeStamp, reference, id);
        return;
    }

    // Check to see if we are connected to a data network.
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

    // If we're not connected then disable the retry Alarm, enable the Connectivity Changed Receiver
    // and add the new checkin directly to the queue. The Connectivity Changed Receiver will listen
    // for when we connect to a network and start this service to retry the checkins.
    if (!isConnected) {
        // No connection so no point triggering an alarm to retry until we're connected.
        alarmManager.cancel(retryQueuedCheckinsPendingIntent);

        // Enable the Connectivity Changed Receiver to listen for connection to a network
        // so we can commit the pending checkins.
        PackageManager pm = getPackageManager();
        ComponentName connectivityReceiver = new ComponentName(this, ConnectivityChangedReceiver.class);
        pm.setComponentEnabledSetting(connectivityReceiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);

        // Add this checkin to the queue.
        addToQueue(timeStamp, reference, id);
    } else {
        // Execute the checkin. If it fails, add it to the retry queue.
        if (reference != null) {
            if (!checkin(timeStamp, reference, id))
                addToQueue(timeStamp, reference, id);
        }

        // Retry the queued checkins.
        ArrayList<String> successfulCheckins = new ArrayList<String>();
        Cursor queuedCheckins = contentResolver.query(QueuedCheckinsContentProvider.CONTENT_URI, null, null,
                null, null);
        try {
            // Retry each checkin.
            while (queuedCheckins.moveToNext()) {
                long queuedTimeStamp = queuedCheckins
                        .getLong(queuedCheckins.getColumnIndex(QueuedCheckinsContentProvider.KEY_TIME_STAMP));
                String queuedReference = queuedCheckins
                        .getString(queuedCheckins.getColumnIndex(QueuedCheckinsContentProvider.KEY_REFERENCE));
                String queuedId = queuedCheckins
                        .getString(queuedCheckins.getColumnIndex(QueuedCheckinsContentProvider.KEY_ID));
                if (queuedReference == null || checkin(queuedTimeStamp, queuedReference, queuedId))
                    successfulCheckins.add(queuedReference);
            }

            // Delete the queued checkins that were successful.
            if (successfulCheckins.size() > 0) {
                StringBuilder sb = new StringBuilder("(" + QueuedCheckinsContentProvider.KEY_REFERENCE + "='"
                        + successfulCheckins.get(0) + "'");
                for (int i = 1; i < successfulCheckins.size(); i++)
                    sb.append(" OR " + QueuedCheckinsContentProvider.KEY_REFERENCE + " = '"
                            + successfulCheckins.get(i) + "'");
                sb.append(")");
                int deleteCount = contentResolver.delete(QueuedCheckinsContentProvider.CONTENT_URI,
                        sb.toString(), null);
                Log.d(TAG, "Deleted: " + deleteCount);
            }

            // If there are still queued checkins then set a non-waking alarm to retry them.
            queuedCheckins.requery();
            if (queuedCheckins.getCount() > 0) {
                long triggerAtTime = System.currentTimeMillis() + PlacesConstants.CHECKIN_RETRY_INTERVAL;
                alarmManager.set(AlarmManager.ELAPSED_REALTIME, triggerAtTime,
                        retryQueuedCheckinsPendingIntent);
            } else
                alarmManager.cancel(retryQueuedCheckinsPendingIntent);
        } finally {
            queuedCheckins.close();
        }
    }
}

From source file:com.android.transmart.services.PlaceCheckinService.java

/**
 * {@inheritDoc}/* w  ww  .  j  a v  a  2  s.c  o m*/
 * Perform a checkin the specified venue. If the checkin fails, add it to the queue and
 * set an alarm to retry.
 * 
 * Query the checkin queue to see if there are pending checkins to be retried.
 */
@Override
protected void onHandleIntent(Intent intent) {
    // Retrieve the details for the checkin to perform.
    String reference = intent.getStringExtra(LocationConstants.EXTRA_KEY_REFERENCE);
    String id = intent.getStringExtra(LocationConstants.EXTRA_KEY_ID);
    long timeStamp = intent.getLongExtra(LocationConstants.EXTRA_KEY_TIME_STAMP, 0);

    // Check if we're running in the foreground, if not, check if
    // we have permission to do background updates.
    boolean backgroundAllowed = cm.getBackgroundDataSetting();
    boolean inBackground = sharedPreferences.getBoolean(LocationConstants.EXTRA_KEY_IN_BACKGROUND, true);

    if (reference != null && !backgroundAllowed && inBackground) {
        addToQueue(timeStamp, reference, id);
        return;
    }

    // Check to see if we are connected to a data network.
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

    // If we're not connected then disable the retry Alarm, enable the Connectivity Changed Receiver
    // and add the new checkin directly to the queue. The Connectivity Changed Receiver will listen
    // for when we connect to a network and start this service to retry the checkins.
    if (!isConnected) {
        // No connection so no point triggering an alarm to retry until we're connected.
        alarmManager.cancel(retryQueuedCheckinsPendingIntent);

        // Enable the Connectivity Changed Receiver to listen for connection to a network
        // so we can commit the pending checkins.
        PackageManager pm = getPackageManager();
        ComponentName connectivityReceiver = new ComponentName(this, ConnectivityChangedReceiver.class);
        pm.setComponentEnabledSetting(connectivityReceiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);

        // Add this checkin to the queue.
        addToQueue(timeStamp, reference, id);
    } else {
        // Execute the checkin. If it fails, add it to the retry queue.
        if (reference != null) {
            if (!checkin(timeStamp, reference, id))
                addToQueue(timeStamp, reference, id);
        }

        // Retry the queued checkins.
        ArrayList<String> successfulCheckins = new ArrayList<String>();
        Cursor queuedCheckins = contentResolver.query(QueuedCheckinsContentProvider.CONTENT_URI, null, null,
                null, null);
        try {
            // Retry each checkin.
            while (queuedCheckins.moveToNext()) {
                long queuedTimeStamp = queuedCheckins
                        .getLong(queuedCheckins.getColumnIndex(QueuedCheckinsContentProvider.KEY_TIME_STAMP));
                String queuedReference = queuedCheckins
                        .getString(queuedCheckins.getColumnIndex(QueuedCheckinsContentProvider.KEY_REFERENCE));
                String queuedId = queuedCheckins
                        .getString(queuedCheckins.getColumnIndex(QueuedCheckinsContentProvider.KEY_ID));
                if (queuedReference == null || checkin(queuedTimeStamp, queuedReference, queuedId))
                    successfulCheckins.add(queuedReference);
            }

            // Delete the queued checkins that were successful.
            if (successfulCheckins.size() > 0) {
                StringBuilder sb = new StringBuilder("(" + QueuedCheckinsContentProvider.KEY_REFERENCE + "='"
                        + successfulCheckins.get(0) + "'");
                for (int i = 1; i < successfulCheckins.size(); i++)
                    sb.append(" OR " + QueuedCheckinsContentProvider.KEY_REFERENCE + " = '"
                            + successfulCheckins.get(i) + "'");
                sb.append(")");
                int deleteCount = contentResolver.delete(QueuedCheckinsContentProvider.CONTENT_URI,
                        sb.toString(), null);
                Log.d(TAG, "Deleted: " + deleteCount);
            }

            // If there are still queued checkins then set a non-waking alarm to retry them.
            queuedCheckins.requery();
            if (queuedCheckins.getCount() > 0) {
                long triggerAtTime = System.currentTimeMillis() + LocationConstants.CHECKIN_RETRY_INTERVAL;
                alarmManager.set(AlarmManager.ELAPSED_REALTIME, triggerAtTime,
                        retryQueuedCheckinsPendingIntent);
            } else
                alarmManager.cancel(retryQueuedCheckinsPendingIntent);
        } finally {
            queuedCheckins.close();
        }
    }
}

From source file:pubsub.io.android.Pubsub.java

/**
 * Detects if we have internet or not, checks both WiFi and 3G.
 * //from   ww  w.  j av  a2  s . co  m
 * @return
 */
public boolean hasInternet() {
    if (DEBUG)
        Log.i(TAG, "hasInternet()");

    ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);

    if (DEBUG)
        Log.i(TAG, "Testing WiFi status");

    // First test wifi for status!
    NetworkInfo netInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        if (DEBUG)
            Log.i(TAG, "WiFi detected, connecting");
        return true;
    }

    if (DEBUG)
        Log.i(TAG, "No WiFi detected, trying mobile");

    netInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        if (DEBUG)
            Log.i(TAG, "Mobile detected, connecting");
        return true;
    }

    if (DEBUG)
        Log.i(TAG, "No Mobile detected, aborting");

    return false;
}

From source file:com.rokolabs.app.common.image.ImageFetcher.java

/**
 * Simple network connection check./*from ww  w  .  j a  va  2 s.  c  o  m*/
 * 
 * @param context
 */
private void checkConnection(Context context) {
    final ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    final NetworkInfo networkInfo = cm.getActiveNetworkInfo();
    if (networkInfo == null || !networkInfo.isConnectedOrConnecting()) {
        //Toast.makeText(context, "No connection!", Toast.LENGTH_SHORT).show();
        Log.e(TAG, "checkConnection - no connection found");
    }
}

From source file:conversandroid.MainActivity.java

/**
 * Checks whether the device is connected to Internet (returns true) or not (returns false)
 *
 * @author http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html
 *//*  w w  w.j av a 2 s .c o m*/
public boolean deviceConnectedToInternet() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    return (activeNetwork != null && activeNetwork.isConnectedOrConnecting());
}

From source file:org.wso2.emm.system.service.api.OTADownload.java

public boolean checkNetworkOnline() {
    ConnectivityManager connectivityManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = connectivityManager.getActiveNetworkInfo();
    boolean status = false;
    if (info != null && info.isConnectedOrConnecting()) {
        status = true;/*w w w  . jav a2  s. c  o m*/
    }

    return status;
}

From source file:me.heron.safefoodscanner.activity.MainActivity.java

private boolean isNetworkAvailable() {

    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(
            Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
    return netInfo != null && netInfo.isConnectedOrConnecting();

}