Example usage for android.location Criteria Criteria

List of usage examples for android.location Criteria Criteria

Introduction

In this page you can find the example usage for android.location Criteria Criteria.

Prototype

public Criteria() 

Source Link

Document

Constructs a new Criteria object.

Usage

From source file:ca.mudar.mtlaucasou.LocationFragmentActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    mAppHelper = (AppHelper) getApplicationContext();
    mActivityHelper = ActivityHelper.createInstance(this);

    prefs = getSharedPreferences(Const.APP_PREFS_NAME, Context.MODE_PRIVATE);
    prefsEditor = prefs.edit();/* w w w .ja  v  a  2 s.c o  m*/

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

    /**
     * Instantiate a LastLocationFinder class. This will be used to find the
     * last known location when the application starts.
     */
    lastLocationFinder = PlatformSpecificImplementationFactory.getLastLocationFinder(this);
    lastLocationFinder.setChangedLocationListener(oneShotLastLocationUpdateListener);
    hasRegisteredSingleUpdateReceiver = true;

    /**
     * Set the last known location as user's current location.
     */
    mAppHelper.setLocation(lastLocationFinder.getLastBestLocation(Const.MAX_DISTANCE, Const.MAX_TIME));

    /**
     * Specify the Criteria to use when requesting location updates while
     * the application is Active.
     */
    criteria = new Criteria();
    if (Const.USE_GPS_WHEN_ACTIVITY_VISIBLE) {
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
    } else {
        criteria.setPowerRequirement(Criteria.POWER_LOW);
    }

    /**
     * Setup the location update Pending Intents.
     */
    Intent activeIntent = new Intent(this, LocationChangedReceiver.class);
    locationListenerPendingIntent = PendingIntent.getBroadcast(this, 0, activeIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    Intent passiveIntent = new Intent(this, PassiveLocationChangedReceiver.class);
    locationListenerPassivePendingIntent = PendingIntent.getBroadcast(this, 0, passiveIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    locationManager.removeUpdates(locationListenerPassivePendingIntent);

    /**
     * Instantiate a Location Update Requester class based on the available
     * platform version. This will be used to request location updates.
     */
    locationUpdateRequester = PlatformSpecificImplementationFactory
            .getLocationUpdateRequester(this.getApplicationContext(), locationManager);

    super.onCreate(savedInstanceState);
}

From source file:com.careme.apvereda.careme.AccumulatorService.java

@Override
public int onStartCommand(Intent intenc, int flags, int idArranque) {
    SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("basicData",
            Context.MODE_PRIVATE);
    String email = sharedPref.getString("email", "");

    //Uncomment to use Nimbees features

    /*if (email.compareTo("") != 0) {
    try {// ww w  .  ja v  a  2 s  .  c om
        // Initialize library calling the init method on the Nimbees Client
        NimbeesClient.init(this);
    } catch (NimbeesException e) {
        e.printStackTrace();
    }
    NimbeesClient.getUserManager().register("email", new NimbeesRegistrationCallback() {
        @Override
        public void onSuccess() {
            /* Registration was successful!
            Toast.makeText(getApplicationContext(),
                    "xito en el registro", Toast.LENGTH_LONG).show();
        }
            
        @Override
        public void onFailure(NimbeesException failure) {
            /* Registration failed
            Toast.makeText(getApplicationContext(),
                    "Fallo en el registro", Toast.LENGTH_LONG).show();
        }
    });
    }
    */
    //Toast.makeText(this,"Servicio arrancado "+ idArranque, Toast.LENGTH_SHORT).show();

    // Obtain a reference to the Location Manager
    locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria crit = new Criteria();
    crit.setAccuracy(Criteria.ACCURACY_FINE);
    crit.setPowerRequirement(Criteria.POWER_LOW);
    provider = locManager.getBestProvider(crit, true);

    // And register to obtain current location updates
    locListener = new LocationListener() {
        public void onLocationChanged(Location loc) {
            // Insert a new entry on History
            History history = new History(loc.getLatitude(), loc.getLongitude(), new Date());
            db.insertHistory(history);
            //Uncomment to use Nimbees features
            /*
            try {
            sendPersonalizado(loc);
            } catch (Exception e) {
            }*/
            /*
            Monitor makes the monitoring of the user to determine if he/she has lost
            */
            monitor(loc);
        }

        @Override
        public void onStatusChanged(String provider, int stat, Bundle extras) {
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onProviderDisabled(String provider) {
        }
    };
    // We want to update the current location every time the user moves MIN_DISTANCE
    locManager.requestLocationUpdates(provider, 0, MIN_DISTANCE, locListener);
    return START_STICKY;
}

From source file:com.dealsmessanger.android.DemoActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);//w w w  . ja  v a 2s.  c  om
    mDisplay = (TextView) findViewById(R.id.display);

    context = getApplicationContext();

    // Check device for Play Services APK. If check succeeds, proceed with GCM registration.
    //        if (checkPlayServices()) {
    //            gcm = GoogleCloudMessaging.getInstance(this);
    //            regid = getRegistrationId(context);
    //
    //            if (regid.isEmpty()) {
    //                registerInBackground();
    //            }
    //        } else {
    //            Log.i(TAG, "No valid Google Play Services APK found.");
    //        }
    registerInBackground();
    // Get the location manager
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    // Define the criteria how to select the location provider
    criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_COARSE); // default

    criteria.setCostAllowed(false);
    // get the best provider depending on the criteria
    provider = locationManager.getBestProvider(criteria, false);

    // the last known location of this provider
    location = locationManager.getLastKnownLocation(provider);

    mylistener = new MyLocationListener();

    if (location != null) {
        mylistener.onLocationChanged(location);
    } else {
        // leads to the settings because there is no last known location
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivity(intent);
    }
    // location updates: at least 1 meter and 200millsecs change
    locationManager.requestLocationUpdates(provider, 200, 1, mylistener);

}

From source file:com.gsma.rcs.ri.messaging.geoloc.EditGeoloc.java

/**
 * Set the location of the device/*from w  w w . j  a v a2  s  .com*/
 */
protected void setMyLocation() {
    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String bestProvider = lm.getBestProvider(criteria, false);
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    Location lastKnownLoc = lm.getLastKnownLocation(bestProvider);
    if (lastKnownLoc != null) {
        mLatitudeEdit.setText(String.valueOf(lastKnownLoc.getLatitude()));
        mLongitudeEdit.setText(String.valueOf(lastKnownLoc.getLongitude()));
        mAccuracyEdit.setText(String.valueOf(lastKnownLoc.getAccuracy()));
    }
    super.onResume();
}

From source file:com.example.testapplication.DialogLocation.java

@SuppressLint("InlinedApi")
@Override/*from w w  w .  java  2  s.  c  om*/
public Dialog onCreateDialog(Bundle savedInstanceState) {
    mProgressBar = new ProgressBar(getActivity(), null, android.R.attr.progressBarStyleLarge);
    mProgressBarInv = new ProgressBar(getActivity(), null, android.R.attr.progressBarStyleLarge);
    mProgressBarInv.setVisibility(ProgressBar.GONE);

    mLocationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);

    mCriteria = new Criteria();
    int criteria = (mGpsPref) ? Criteria.POWER_HIGH : Criteria.POWER_MEDIUM;
    mCriteria.setPowerRequirement(criteria);

    mProvider = mLocationManager.getBestProvider(mCriteria, true);
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    TelephonyManager tm = (TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE);
    int telephonyInfo = tm.getNetworkType();

    boolean networkAvailable = true;

    if ((telephonyInfo == TelephonyManager.NETWORK_TYPE_UNKNOWN && !networkInfo.isConnected())
            || !mLocationManager.isProviderEnabled("network")) {
        networkAvailable = false;
    }

    int locationMode = -1;
    int locationType = -1;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        try {
            locationMode = Settings.Secure.getInt(getActivity().getContentResolver(),
                    Settings.Secure.LOCATION_MODE);
        } catch (SettingNotFoundException e) {
            e.printStackTrace();
        }

        if (locationMode == Settings.Secure.LOCATION_MODE_OFF
                || (!networkAvailable && (mProvider.matches("network"))))
            locationType = NO_LOCATION_SERVICES;
        else if (mGpsPref && (locationMode == Settings.Secure.LOCATION_MODE_SENSORS_ONLY
                || locationMode == Settings.Secure.LOCATION_MODE_HIGH_ACCURACY))
            locationType = (locationMode == Settings.Secure.LOCATION_MODE_SENSORS_ONLY || !networkAvailable)
                    ? USING_ONLY_GPS_LOCATION
                    : USING_GPS_LOCATION_NETWORK_AVAILABLE;
        else if (mProvider.matches("network") && (locationMode == Settings.Secure.LOCATION_MODE_BATTERY_SAVING
                || locationMode == Settings.Secure.LOCATION_MODE_HIGH_ACCURACY))
            locationType = USING_NETWORK_LOCATION;

    } else {
        if (mProvider.matches("passive") || !networkAvailable
                && (mProvider.matches("network") || (!mGpsPref && mProvider.matches("gps"))))
            locationType = NO_LOCATION_SERVICES;
        else if (mProvider.matches("gps") && mGpsPref)
            locationType = ((mProvider.matches("gps")) || !networkAvailable) ? USING_ONLY_GPS_LOCATION
                    : USING_GPS_LOCATION_NETWORK_AVAILABLE;
        else if (mProvider.matches("network"))
            locationType = USING_NETWORK_LOCATION;
    }

    switch (locationType) {
    case NO_LOCATION_SERVICES:
        builder.setTitle(DIALOG_LOCATION_NO_LOCATION_SERVICES_TITLE);
        builder.setMessage(DIALOG_LOCATION_NO_LOCATION_SERVICES_MESSAGE);
        builder.setNeutralButton(DIALOG_LOCATION_BUTTON_SETTINGS, noNetworkButton);
        mAbortRequest = true;
        break;
    case USING_ONLY_GPS_LOCATION:
        builder.setTitle(DIALOG_LOCATION_UPDATING_GPS_TITLE);
        builder.setMessage(DIALOG_LOCATION_ONLY_GPS_MESSAGE);
        builder.setNeutralButton(DIALOG_LOCATION_BUTTON_SETTINGS, noNetworkButton);
        builder.setView(mProgressBar);
        break;
    case USING_GPS_LOCATION_NETWORK_AVAILABLE:
        builder.setTitle(DIALOG_LOCATION_UPDATING_GPS_TITLE);
        builder.setPositiveButton(DIALOG_LOCATION_USE_NETWORK, null);
        builder.setView(mProgressBar);
        break;
    case USING_NETWORK_LOCATION:
        builder.setView(mProgressBar);
        builder.setTitle(DIALOG_LOCATION_UPDATING_NETWORK_TITLE);
        break;
    }

    builder.setNegativeButton(DIALOG_LOCATION_CANCEL, cancelListener);
    builder.setOnKeyListener(new DialogInterface.OnKeyListener() {

        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                mCallback.onLocationFound(null, mFragmentId);
                mLocationManager.removeUpdates(DialogLocation.this);
                Toast.makeText(getActivity(), "Location request cancelled", Toast.LENGTH_SHORT).show();
                dialog.cancel();
                return true;
            }
            return false;
        }
    });

    mRealDialog = builder.create();
    mRealDialog.setOnShowListener(usingNetwork);
    mRealDialog.setCanceledOnTouchOutside(false);
    return mRealDialog;
}

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

@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
        final Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.activity_car_browse, container, false);

    final SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
    provider = locationManager.getBestProvider(new Criteria(), false);

    return view;//  w w w  . ja  v  a 2  s  .  c  o  m
}

From source file:com.quantcast.measurement.service.QCLocation.java

void setupLocManager(Context appContext) {
    if (appContext == null)
        return;//from www .  j  ava2s  .  c o m

    _locManager = (LocationManager) appContext.getSystemService(Context.LOCATION_SERVICE);
    if (_locManager != null) {
        //specifically set our Criteria. All we need is a general location
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_COARSE);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(false);
        criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
        criteria.setSpeedRequired(false);

        _myProvider = _locManager.getBestProvider(criteria, true);

        _geocoder = new Geocoder(appContext);
    }
    QCLog.i(TAG, "Setting location provider " + _myProvider);
}

From source file:nodomain.freeyourgadget.gadgetbridge.externalevents.AlarmReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    if (!GBApplication.getPrefs().getBoolean("send_sunrise_sunset", false)) {
        LOG.info("won't send sunrise and sunset events (disabled in preferences)");
        return;/*from w w w .  j  ava2  s .c  om*/
    }
    LOG.info("will resend sunrise and sunset events");

    final GregorianCalendar dateTimeTomorrow = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
    dateTimeTomorrow.set(Calendar.HOUR, 0);
    dateTimeTomorrow.set(Calendar.MINUTE, 0);
    dateTimeTomorrow.set(Calendar.SECOND, 0);
    dateTimeTomorrow.set(Calendar.MILLISECOND, 0);
    dateTimeTomorrow.add(GregorianCalendar.DAY_OF_MONTH, 1);

    /*
     * rotate ids ud reuse the id from two days ago for tomorrow, this way we will have
     * sunrise /sunset for 3 days while sending only sunrise/sunset per day
     */
    byte id_tomorrow = (byte) ((dateTimeTomorrow.getTimeInMillis() / (1000L * 60L * 60L * 24L)) % 3);

    GBApplication.deviceService().onDeleteCalendarEvent(CalendarEventSpec.TYPE_SUNRISE, id_tomorrow);
    GBApplication.deviceService().onDeleteCalendarEvent(CalendarEventSpec.TYPE_SUNSET, id_tomorrow);

    Prefs prefs = GBApplication.getPrefs();

    float latitude = prefs.getFloat("location_latitude", 0);
    float longitude = prefs.getFloat("location_longitude", 0);
    LOG.info("got longitude/latitude from preferences: " + latitude + "/" + longitude);

    if (ActivityCompat.checkSelfPermission(context,
            Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
            && prefs.getBoolean("use_updated_location_if_available", false)) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String provider = locationManager.getBestProvider(criteria, false);
        if (provider != null) {
            Location lastKnownLocation = locationManager.getLastKnownLocation(provider);
            if (lastKnownLocation != null) {
                latitude = (float) lastKnownLocation.getLatitude();
                longitude = (float) lastKnownLocation.getLongitude();
                LOG.info("got longitude/latitude from last known location: " + latitude + "/" + longitude);
            }
        }
    }
    GregorianCalendar[] sunriseTransitSetTomorrow = SPA.calculateSunriseTransitSet(dateTimeTomorrow, latitude,
            longitude, DeltaT.estimate(dateTimeTomorrow));

    CalendarEventSpec calendarEventSpec = new CalendarEventSpec();
    calendarEventSpec.durationInSeconds = 0;
    calendarEventSpec.description = null;

    calendarEventSpec.type = CalendarEventSpec.TYPE_SUNRISE;
    calendarEventSpec.title = "Sunrise";
    if (sunriseTransitSetTomorrow[0] != null) {
        calendarEventSpec.id = id_tomorrow;
        calendarEventSpec.timestamp = (int) (sunriseTransitSetTomorrow[0].getTimeInMillis() / 1000);
        GBApplication.deviceService().onAddCalendarEvent(calendarEventSpec);
    }

    calendarEventSpec.type = CalendarEventSpec.TYPE_SUNSET;
    calendarEventSpec.title = "Sunset";
    if (sunriseTransitSetTomorrow[2] != null) {
        calendarEventSpec.id = id_tomorrow;
        calendarEventSpec.timestamp = (int) (sunriseTransitSetTomorrow[2].getTimeInMillis() / 1000);
        GBApplication.deviceService().onAddCalendarEvent(calendarEventSpec);
    }
}

From source file:fiser.Activities.MainActivity.java

private void listaRecargar(boolean cercanos) {
    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    sitioList.clear();/*w ww. ja  v  a 2s  . c  om*/
    if (!cercanos) {
        for (Sitio sitio : Sitio.getSitio(this))
            sitioList.add(sitio);
    } else {
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String provider = locationManager.getBestProvider(criteria, true);
        if (ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            for (Sitio sitio : Sitio.getSitio(this))
                sitioList.add(sitio);
        } else {
            Location location = locationManager.getLastKnownLocation(provider);
            for (Sitio sitio : Sitio.getSitio(this)) {
                Location loc = new Location("temp");
                loc.setLatitude(sitio.latitud);
                loc.setLongitude(sitio.longitud);
                float distance = location.distanceTo(loc);
                int cercaniaMinimaInt = sharedPref.getInt(getString(R.string.cercaniaMinima),
                        getResources().getInteger(R.integer.cercaniaMinimaDefault));
                if (cercaniaMinimaInt * 1000 > distance)
                    sitioList.add(sitio);
            }
        }
    }
    adapter.notifyDataSetChanged();
}

From source file:ca.mudar.mtlaucasou.BaseListFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mActivityHelper = ActivityHelper.createInstance(getActivity());
    mAppHelper = ((AppHelper) getActivity().getApplicationContext());

    locationManager = (LocationManager) getSupportActivity().getSystemService(Context.LOCATION_SERVICE);
    locationListener = new MyLocationListener();
    criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_COARSE);

    SharedPreferences prefs = getSupportActivity().getSharedPreferences(Const.APP_PREFS_NAME,
            Context.MODE_PRIVATE);
    hasFollowLocationChanges = prefs.getBoolean(Const.PrefsNames.FOLLOW_LOCATION_CHANGES, false);

    Location myLocation = mAppHelper.getLocation();

    mHandler = new NotifyingAsyncQueryHandler(getActivity().getContentResolver(), this);

    if (mCursor != null) {
        getActivity().stopManagingCursor(mCursor);
        mCursor = null;//from   w  w w .ja  v a  2s.  c o  m
    }

    setListAdapter(null);
    mHandler.cancelOperation(QUERY_TOKEN);

    /**
     * Update the projection alias to calculate the distance based on the
     * current Location.
     */
    String mSort;
    if (mAppHelper.getListSort().equals(PrefsValues.LIST_SORT_DISTANCE) && myLocation != null) {
        mSort = PlacemarkColumns.PLACEMARK_DISTANCE + " ASC ";
    } else {
        mSort = defaultSort;
    }

    mCursor = getActivity().getContentResolver().query(mActivityHelper.getContentUri(indexSection),
            PLACEMARKS_SUMMARY_PROJECTION, null, null, mSort);
    getActivity().startManagingCursor(mCursor);

    mAdapter = new PlacemarksCursorAdapter(getActivity(), R.layout.fragment_list_item_placemarks, mCursor,
            new String[] { PlacemarkColumns.PLACEMARK_NAME, PlacemarkColumns.PLACEMARK_ADDRESS },
            new int[] { R.id.placemark_name, R.id.placemark_address }, 0);

    setListAdapter(mAdapter);

    mHandler.startQuery(QUERY_TOKEN, null, mActivityHelper.getContentUri(indexSection),
            PLACEMARKS_SUMMARY_PROJECTION, null, null, mSort);
}