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:com.rareventure.android.GpsReader.java

public void turnOn() {
    synchronized (lock) {
        //          Log.d(GpsTrailerService.TAG,"Turning on gps");
        if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            GTG.alert(GTGEvent.ERROR_GPS_DISABLED);
            return;
        }/*ww w  .ja va 2 s . c  o m*/
        if (ActivityCompat.checkSelfPermission(this.ctx,
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            GTG.alert(GTGEvent.ERROR_GPS_NO_PERMISSION);
            //            Log.d(GpsTrailerService.TAG,"Failed no permission");
            return;
        }

        if (gpsOn) {
            //            Log.d(GpsTrailerService.TAG,"Gps already on");
            return; //already on
        }
        gpsOn = true;

        //         Log.d(GpsTrailerService.TAG,"Really turning on");
        Criteria criteria = new Criteria();
        criteria.setSpeedRequired(false);
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(false);

        String providerName = lm.getBestProvider(criteria, true);
        lm.requestLocationUpdates(providerName, prefs.gpsRecurringTimeMs, 0, locationListener, looper);
    }
}

From source file:tjs.tuneramblr.TuneramblrMobileActivity.java

/** Called when the activity is first created. */
@Override//w  w  w . j  a  v  a2  s .  c o  m
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // set the current view
    setContentView(R.layout.main);

    // retrieve the fragments
    checkinFragment = new CheckinFragment();
    loginFragment = new LoginFragment();

    // determine which fragment we want to show
    UserInfoDS userInfoDs = new UserInfoDS(getApplicationContext());
    UserInfo userInfo = null;
    try {
        userInfo = userInfoDs.readUserInfo();
    } catch (IOException e) {
        userInfo = null;
    }

    Fragment fragment = null;
    if ((userInfo != null) && (userInfo.getUsername() != null) && (userInfo.getPassword() != null)) {
        fragment = checkinFragment;
    } else {
        fragment = loginFragment;
    }

    // add the fragment to the the main layout
    getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, fragment).commit();

    // Get references to the managers
    packageManager = getPackageManager();
    notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    // Get a reference to the Shared Preferences and a Shared Preference
    // Editor.
    prefs = getSharedPreferences(TuneramblrConstants.SHARED_PREFERENCE_FILE, Context.MODE_PRIVATE);
    prefsEditor = prefs.edit();

    // Instantiate a SharedPreferenceSaver class based on the available
    // platform version.
    // This will be used to save shared preferences
    sharedPreferenceSaver = PlatformSpecificImplementationFactory.getSharedPreferenceSaver(this);

    // Save that we've been run once.
    prefsEditor.putBoolean(TuneramblrConstants.SP_KEY_RUN_ONCE, true);
    sharedPreferenceSaver.savePreferences(prefsEditor, false);

    // Specify the Criteria to use when requesting location updates while
    // the application is Active
    criteria = new Criteria();
    if (TuneramblrConstants.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);

    // 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);

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

    // Create an Intent Filter to listen for checkins
    newCheckinReceiverName = new ComponentName(this, NewCheckinReceiver.class);
    newCheckinFilter = new IntentFilter(TuneramblrConstants.NEW_CHECKIN_ACTION);

    // check if anything has changed
    if (getIntent().hasExtra(TuneramblrConstants.EXTRA_KEY_ID)) {
        // nadda right now
    }
}

From source file:com.eutectoid.dosomething.PickerActivity.java

@Override
protected void onStart() {
    super.onStart();
    if (FRIEND_PICKER.equals(getIntent().getData())) {
        try {/*from   ww  w  .  ja va2s  .  c  o m*/
            friendPickerFragment.loadData(false);
        } catch (Exception ex) {
            onError(ex);
        }
    } else if (PLACE_PICKER.equals(getIntent().getData())) {
        try {
            Location location = null;
            Criteria criteria = new Criteria();

            LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            String bestProvider = locationManager.getBestProvider(criteria, false);
            // API 23: we have to check if ACCESS_FINE_LOCATION and/or ACCESS_COARSE_LOCATION permission are granted
            if (ContextCompat.checkSelfPermission(this,
                    android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                    || ContextCompat.checkSelfPermission(this,
                            android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                location = locationManager.getLastKnownLocation(bestProvider);
                if (locationManager.isProviderEnabled(bestProvider) && locationListener == null) {
                    locationListener = new LocationListener() {
                        @Override
                        public void onLocationChanged(Location location) {
                            boolean updateLocation = true;
                            Location prevLocation = placePickerFragment.getLocation();
                            if (prevLocation != null) {
                                updateLocation = location.distanceTo(prevLocation) >= LOCATION_CHANGE_THRESHOLD;
                            }
                            if (updateLocation) {
                                placePickerFragment.setLocation(location);
                                placePickerFragment.loadData(true);
                            }
                        }

                        @Override
                        public void onStatusChanged(String s, int i, Bundle bundle) {
                        }

                        @Override
                        public void onProviderEnabled(String s) {
                        }

                        @Override
                        public void onProviderDisabled(String s) {
                        }
                    };
                    locationManager.requestLocationUpdates(bestProvider, 1, LOCATION_CHANGE_THRESHOLD,
                            locationListener, Looper.getMainLooper());
                }
            }
            if (location != null) {
                placePickerFragment.setLocation(location);
                placePickerFragment.setRadiusInMeters(SEARCH_RADIUS_METERS);
                placePickerFragment.setSearchText(SEARCH_TEXT);
                placePickerFragment.setResultsLimit(SEARCH_RESULT_LIMIT);
                placePickerFragment.loadData(false);
            }
        } catch (Exception ex) {
            onError(ex);
        }
    }
}

From source file:com.radioactiveyak.location_best_practices.UI.PlaceActivity.java

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

    // Inflate the layout
    setContentView(R.layout.main);// ww  w  .  j a v  a 2 s .  c  o  m

    // Get a handle to the Fragments
    placeListFragment = (PlaceListFragment) getSupportFragmentManager().findFragmentById(R.id.list_fragment);
    checkinFragment = (CheckinFragment) getSupportFragmentManager().findFragmentById(R.id.checkin_fragment);

    // Get references to the managers
    packageManager = getPackageManager();
    notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    // Get a reference to the Shared Preferences and a Shared Preference Editor.
    prefs = getSharedPreferences(PlacesConstants.SHARED_PREFERENCE_FILE, Context.MODE_PRIVATE);
    prefsEditor = prefs.edit();

    // Instantiate a SharedPreferenceSaver class based on the available platform version.
    // This will be used to save shared preferences
    sharedPreferenceSaver = PlatformSpecificImplementationFactory.getSharedPreferenceSaver(this);

    // Save that we've been run once.
    prefsEditor.putBoolean(PlacesConstants.SP_KEY_RUN_ONCE, true);
    sharedPreferenceSaver.savePreferences(prefsEditor, false);

    // Specify the Criteria to use when requesting location updates while the application is Active
    criteria = new Criteria();
    if (PlacesConstants.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);

    // 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);

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

    // Create an Intent Filter to listen for checkins
    newCheckinReceiverName = new ComponentName(this, NewCheckinReceiver.class);
    newCheckinFilter = new IntentFilter(PlacesConstants.NEW_CHECKIN_ACTION);

    // Check to see if an Place ID has been specified in the launch Intent.
    // If so, we should display the details for the specified venue.
    if (getIntent().hasExtra(PlacesConstants.EXTRA_KEY_ID)) {
        Intent intent = getIntent();
        String key = intent.getStringExtra(PlacesConstants.EXTRA_KEY_ID);
        if (key != null) {
            selectDetail(null, key);
            // Remove the ID from the Intent (so that a resume doesn't reselect).
            intent.removeExtra(PlacesConstants.EXTRA_KEY_ID);
            setIntent(intent);
        }
    }
}

From source file:obdii.starter.automotive.iot.ibm.com.iot4a_obdii.Home.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

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

    progressBar = new ProgressBar(this);
    progressBar.setVisibility(View.GONE);
    progressBar.setIndeterminate(true);/* w w w  .  j  a  v a2s  . co  m*/
    progressBar.setScaleX(0.5f);
    progressBar.setScaleY(0.5f);

    supportActionBar = getSupportActionBar();
    supportActionBar.setDisplayShowCustomEnabled(true);
    supportActionBar.setCustomView(progressBar);

    changeNetwork = (Button) findViewById(R.id.changeNetwork);
    changeFrequency = (Button) findViewById(R.id.changeFrequency);

    obdBridge.initializeObdParameterList(this);

    try {
        checkForDisclaimer();
    } catch (IOException e) {
        e.printStackTrace();
    }
    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}

From source file:com.dat255.ht13.grupp23.view.MapView.java

/**
 * Initiating the GoogleMap and all necessary items for the configuration
 * /*  w ww. java 2s.co m*/
 * @param fragmentActivity
 */
private void initiateMap(FragmentActivity fragmentActivity) {
    // Getting Google Play availability status
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(fragmentActivity.getBaseContext());

    // Showing status
    if (status != ConnectionResult.SUCCESS) { // Google Play Services are
        // not available

        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, fragmentActivity, requestCode);
        dialog.show();

    } else { // Google Play Services are available

        // Getting reference to the SupportMapFragment of activity_main.xml
        SupportMapFragment fm = (SupportMapFragment) fragmentActivity.getSupportFragmentManager()
                .findFragmentById(R.id.map);

        // Getting GoogleMap object from the fragment
        googleMap = fm.getMap();

        // Enabling MyLocation Layer of Google Map
        googleMap.setMyLocationEnabled(true);

        // Getting LocationManager object from System Service
        // LOCATION_SERVICE
        LocationManager locationManager = (LocationManager) fragmentActivity
                .getSystemService(Context.LOCATION_SERVICE);

        // Creating a criteria object to retrieve provider
        Criteria criteria = new Criteria();

        // Getting the name of the best provider
        String provider = locationManager.getBestProvider(criteria, true);

        // Getting Current Location
        Location location = locationManager.getLastKnownLocation(provider);

        if (location != null) {
            onLocationChanged(location);
            locationManager.requestLocationUpdates(provider, 20000, 0, this);
        }
    }

}

From source file:com.johan.vertretungsplan_2.SelectSchoolActivity.java

private void showListGeo() {
    final LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_COARSE); // no GPS
    final String provider = locationManager.getBestProvider(criteria, true);

    if (provider == null) {
        Log.d("vertretungsplan", "provider==null");
        tvLocateString.setText(R.string.geolocate_disabled);
        status = Status.LIST;/* w ww.ja  v a 2 s.co  m*/
        return;
    }
    locationManager.requestLocationUpdates(provider, 0, 0, new LocationListener() {
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onProviderDisabled(String provider) {
        }

        @Override
        public void onLocationChanged(Location location) {
            if (!visible)
                return;
            if (location != null) {
                double lat = location.getLatitude();
                double lon = location.getLongitude();
                for (Schule school : schools) {
                    float[] result = new float[1];
                    Location.distanceBetween(lat, lon, school.getGeo()[0], school.getGeo()[1], result);
                    school.setDistance(result[0]);
                    Log.d("vertretungsplan", school.getName() + ": " + school.getDistance());
                }
                Collections.sort(schools, new DistanceSchoolComparator());
                lstSchools.setAdapter(new SchoolsAdapter(SelectSchoolActivity.this, schools, true));
            }
            tvLocateString.setText(R.string.alphabetic_list);
            ivLocationIcon.setImageResource(R.drawable.ic_action_view_as_list);
            status = Status.GEO;
        }
    });
}

From source file:org.microg.gms.maps.GoogleMapImpl.java

private GoogleMapImpl(Context context, GoogleMapOptions options) {
    this.context = context;
    Context appContext = context;
    if (appContext.getApplicationContext() != null)
        appContext = appContext.getApplicationContext();
    Context wrappedContext = ApplicationContextWrapper.gmsContextWithAttachedApplicationContext(appContext);
    backendMap = new BackendMap(wrappedContext, this);
    uiSettings = new UiSettingsImpl(this);
    projection = new ProjectionImpl(backendMap.getViewport());
    this.options = options;

    criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_COARSE);
    criteria.setPowerRequirement(Criteria.POWER_MEDIUM);

    if (options != null)
        initFromOptions();//  ww w. j  a  v  a2s  .co  m
}

From source file:heartware.com.heartware_master.FB_PickerActivity.java

@Override
protected void onStart() {
    super.onStart();
    if (FRIEND_PICKER.equals(getIntent().getData())) {
        try {//from ww  w  .java2  s .  com
            friendPickerFragment.loadData(false);
        } catch (Exception ex) {
            onError(ex);
        }
    } else if (PLACE_PICKER.equals(getIntent().getData())) {
        try {
            Location location = null;
            Criteria criteria = new Criteria();
            LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            String bestProvider = locationManager.getBestProvider(criteria, false);
            if (bestProvider != null) {
                location = locationManager.getLastKnownLocation(bestProvider);
                if (locationManager.isProviderEnabled(bestProvider) && locationListener == null) {
                    locationListener = new LocationListener() {
                        @Override
                        public void onLocationChanged(Location location) {
                            boolean updateLocation = true;
                            Location prevLocation = placePickerFragment.getLocation();
                            if (prevLocation != null) {
                                updateLocation = location.distanceTo(prevLocation) >= LOCATION_CHANGE_THRESHOLD;
                            }
                            if (updateLocation) {
                                placePickerFragment.setLocation(location);
                                placePickerFragment.loadData(true);
                            }
                        }

                        @Override
                        public void onStatusChanged(String s, int i, Bundle bundle) {
                        }

                        @Override
                        public void onProviderEnabled(String s) {
                        }

                        @Override
                        public void onProviderDisabled(String s) {
                        }
                    };
                    locationManager.requestLocationUpdates(bestProvider, 1, LOCATION_CHANGE_THRESHOLD,
                            locationListener, Looper.getMainLooper());
                }
            }
            if (location == null) {
                String model = Build.MODEL;
                if (model.equals("sdk") || model.equals("google_sdk") || model.contains("x86")) {
                    // this may be the emulator, pretend we're in an exotic place
                    location = TEMPE_AZ_LOCATION;
                }
                location = TEMPE_AZ_LOCATION; // @TODO HARDCODED location
            }
            if (location != null) {
                location = TEMPE_AZ_LOCATION;
                placePickerFragment.setLocation(location);
                placePickerFragment.setRadiusInMeters(SEARCH_RADIUS_METERS);
                placePickerFragment.setSearchText(SEARCH_TEXT);
                placePickerFragment.setResultsLimit(SEARCH_RESULT_LIMIT);
                placePickerFragment.loadData(false);
            } else {
                onError(getResources().getString(R.string.no_location_error), true);
            }
        } catch (Exception ex) {
            onError(ex);
        }
    }
}

From source file:ch.hesso.master.sweetcity.activity.map.MapActivity.java

public void showCurrentPosition() {
    if (map == null)
        return;/*from  w  w  w.  ja  va  2  s  .c o m*/

    // Enabling MyLocation Layer of Google Map
    map.setMyLocationEnabled(true);

    Criteria lightCriteria = new Criteria();
    lightCriteria.setAccuracy(Criteria.ACCURACY_COARSE);
    lightCriteria.setAltitudeRequired(false);
    lightCriteria.setBearingRequired(false);
    lightCriteria.setCostAllowed(false);
    lightCriteria.setHorizontalAccuracy(Criteria.ACCURACY_MEDIUM);
    lightCriteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
    lightCriteria.setSpeedAccuracy(Criteria.NO_REQUIREMENT);
    lightCriteria.setSpeedRequired(false);

    listener = new MapLocationListener(map);

    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    locationManager.requestSingleUpdate(lightCriteria, listener, null);
    locationProvider = locationManager.getBestProvider(new Criteria(), true);
    Location location = locationManager.getLastKnownLocation(locationProvider);

    if (location != null) {
        listener.onLocationChanged(location);
        map.animateCamera(CameraUpdateFactory.zoomTo(15));
    }
}