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.findcab.driver.activity.Signup.java

/**
 * ?GPS?//from  ww w  . j  av a  2s .  co  m
 */
private void initLocation() {

    LocationManager locationManager;
    String serviceName = Context.LOCATION_SERVICE;
    locationManager = (LocationManager) this.getSystemService(serviceName);
    // ?
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);
    criteria.setCostAllowed(true);
    criteria.setPowerRequirement(Criteria.POWER_LOW);

    String provider = locationManager.getBestProvider(criteria, true);
    Location location = locationManager.getLastKnownLocation(provider);
    if (location != null) {

        lat = location.getLatitude();
        lng = location.getLongitude();

    }
}

From source file:org.voltdb.MainActivity.java

private void identifyLocation() {
    if (BuildConfig.voter_has_location) {
        mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        if (!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            // check if enabled and if not send user to the GSP settings
            // Better solution would be to display a dialog and suggesting to
            // go to the settings
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(intent);/* www  .j a  va2  s. c om*/
        }

        // Define the criteria how to select the locatioin provider -> use default
        Criteria criteria = new Criteria();
        mLocationProvider = mLocationManager.getBestProvider(criteria, false);
        if (mLocationProvider == null) {
            mLocationProvider = LocationManager.GPS_PROVIDER;
        }
    }
}

From source file:com.detroitteatime.autocarfinder.Main.java

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

    mainLayout = (LinearLayout) this.getLayoutInflater().inflate(R.layout.main, null);

    setContentView(mainLayout);/*  ww  w . j  a v a2  s .  c  o  m*/

    // Possible work around for market launches. See
    // http://code.google.com/p/android/issues/detail?id=2373
    // for more details. Essentially, the market launches the main activity
    // on top of other activities.
    // we never want this to happen. Instead, we check if we are the root
    // and if not, we finish.
    if (!isTaskRoot()) {
        final Intent intent = getIntent();
        final String intentAction = intent.getAction();
        if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && intentAction != null
                && intentAction.equals(Intent.ACTION_MAIN)) {
            // Log.w("My Code",
            // "Main Activity is not the root.  Finishing Main Activity instead of launching.");
            finish();
            return;
        }
    }

    // set up buttons
    start = (Button) findViewById(R.id.start);

    manual = (Button) findViewById(R.id.manual);
    // progress = (ProgressBar) findViewById(R.id.progressBar1);

    start.setOnClickListener(this);
    start.getBackground().setColorFilter(Color.parseColor(COLOR), PorterDuff.Mode.MULTIPLY);

    manual.setOnClickListener(this);
    manual.getBackground().setColorFilter(Color.parseColor(COLOR), PorterDuff.Mode.MULTIPLY);

    monitor = (FrameLayout) findViewById(R.id.frameLayout1);

    data1 = this.getSharedPreferences("storage", 0);
    editor1 = data1.edit();

    // firstTime = data1.getBoolean("first_time", true);

    editor1.putBoolean("first_time", false);
    editor1.commit();

    pi = PendingIntent.getActivity(this, 0, new Intent(this, Main.class), 0);

    data1 = getSharedPreferences("storage", 0);
    editor1 = data1.edit();

    // set a global layout listener which will be called when the layout
    // pass is completed and the view is drawn

    FragmentManager myFragmentManager = getSupportFragmentManager();
    mySupportMapFragment = (SupportMapFragment) myFragmentManager.findFragmentById(R.id.map);

    if (MapsInitializer.initialize(this) != ConnectionResult.SUCCESS) {
        Toast.makeText(this, "Map failed to initialize.", Toast.LENGTH_SHORT).show();

    }

    map = mySupportMapFragment.getMap();

    manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    // Define the criteria how to select the locatioin provider -> use
    // default
    criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);
    provider = manager.getBestProvider(criteria, false);
    manager.requestLocationUpdates(provider, 1000, 1, this);

    navigate = (Button) findViewById(R.id.navigate);
    navigate.setOnClickListener(this);

    type = (Button) findViewById(R.id.satellite);
    type.setOnClickListener(this);

}

From source file:com.facebook.samples.placepicker.PlacePickerSampleActivity.java

private void onClickGPS() {
    try {/*from w w w  .  j  a v  a  2 s . com*/
        if (lastKnownLocation == null) {
            Criteria criteria = new Criteria();
            String bestProvider = locationManager.getBestProvider(criteria, false);
            if (bestProvider != null) {
                lastKnownLocation = locationManager.getLastKnownLocation(bestProvider);
            }
        }
        if (lastKnownLocation == null) {
            String model = android.os.Build.MODEL;
            if (model.equals("sdk") || model.equals("google_sdk") || model.contains("x86")) {
                // Looks like they are on an emulator, pretend we're in Paris if we don't have a
                // location set.
                lastKnownLocation = PARIS_LOCATION;
            } else {
                onError(new Exception(getString(R.string.no_location)));
                return;
            }
        }
        startPickPlaceActivity(lastKnownLocation);
    } catch (Exception ex) {
        onError(ex);
    }
}

From source file:com.marianhello.cordova.bgloc.LocationUpdateService.java

@Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "OnCreate");

        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
        toneGenerator = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100);
        connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

        // Stop-detection PI
        stationaryAlarmPI = PendingIntent.getBroadcast(this, 0, new Intent(STATIONARY_ALARM_ACTION), 0);
        registerReceiver(stationaryAlarmReceiver, new IntentFilter(STATIONARY_ALARM_ACTION));

        // Stationary region PI
        stationaryRegionPI = PendingIntent.getBroadcast(this, 0, new Intent(STATIONARY_REGION_ACTION),
                PendingIntent.FLAG_CANCEL_CURRENT);
        registerReceiver(stationaryRegionReceiver, new IntentFilter(STATIONARY_REGION_ACTION));

        // Stationary location monitor PI
        stationaryLocationPollingPI = PendingIntent.getBroadcast(this, 0,
                new Intent(STATIONARY_LOCATION_MONITOR_ACTION), 0);
        registerReceiver(stationaryLocationMonitorReceiver, new IntentFilter(STATIONARY_LOCATION_MONITOR_ACTION));

        // One-shot PI (TODO currently unused)
        singleUpdatePI = PendingIntent.getBroadcast(this, 0, new Intent(SINGLE_LOCATION_UPDATE_ACTION),
                PendingIntent.FLAG_CANCEL_CURRENT);
        registerReceiver(singleUpdateReceiver, new IntentFilter(SINGLE_LOCATION_UPDATE_ACTION));

        /////*from w  ww . jav a  2  s . c om*/
        // DISABLED
        // Listen to Cell-tower switches (NOTE does not operate while suspended)
        //telephonyManager.listen(phoneStateListener, LISTEN_CELL_LOCATION);
        //

        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);

        wakeLock.acquire();

        // Location criteria
        criteria = new Criteria();
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setSpeedRequired(true);
        criteria.setCostAllowed(true);
    }

From source file:net.mceoin.cominghome.LocationService.java

private void backgroundThreadProcessing() {
    secondsToSleep = 30;/*  w ww.j av  a2  s  .co m*/
    while (runBackgroundThread) {
        if (locationManager == null) {
            initLocationManager();
        }
        try {
            if (debug)
                Log.d(TAG, "sleeping " + secondsToSleep + " seconds");
            Thread.sleep(secondsToSleep * 1000);
            if (secondsToSleep < MAXSLEEP_WHILE_NOT_MOVING) {
                secondsToSleep += 15;
            }
        } catch (InterruptedException e) {
            //                e.printStackTrace();
            if (debug)
                Log.d(TAG, "wake up!");
        }
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        String provider = locationManager.getBestProvider(criteria, true);

        //            provider = LocationManager.GPS_PROVIDER;
        Location location = locationManager.getLastKnownLocation(provider);
        if (mLocationClient.isConnected()) {
            if (debug)
                Log.d(TAG, "mLocationClient is connected");
            location = mLocationClient.getLastLocation();
        }
        if (debug)
            Log.d(TAG, "location=" + location);
        if (myLocation == null) {
            myLocation = location;
            broadcastLocationChanged(myLocation);
        } else {
            float dist = distFrom(myLocation, location);
            if (debug)
                Log.d(TAG, "dist=" + dist);
            if ((checkinRequested) || (dist > 20)) {
                myLocation = location;
                broadcastLocationChanged(myLocation);
                checkinRequested = false;
                if (secondsToSleep > MAXSLEEP_WHILE_MOVING) {
                    // if we're moving, don't sleep too much
                    secondsToSleep = MAXSLEEP_WHILE_MOVING;
                }
            }
        }

    }
}

From source file:com.appnexus.opensdk.AdRequest.java

private AdRequest(AdRequester adRequester, int httpRetriesLeft, int blankRetriesLeft) {
    owner = adRequester.getOwner();//from   www  .j a v a  2 s . c om
    this.requester = adRequester;
    this.httpRetriesLeft = httpRetriesLeft;
    this.blankRetriesLeft = blankRetriesLeft;
    this.placementId = owner.getPlacementID();
    context = owner.getContext();
    String aid = android.provider.Settings.Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);

    // Do we have access to location?
    if (context.checkCallingOrSelfPermission(
            "android.permission.ACCESS_FINE_LOCATION") == PackageManager.PERMISSION_GRANTED
            || context.checkCallingOrSelfPermission(
                    "android.permission.ACCESS_COARSE_LOCATION") == PackageManager.PERMISSION_GRANTED) {
        // Get lat, long from any GPS information that might be currently
        // available
        LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        Location lastLocation = lm.getLastKnownLocation(lm.getBestProvider(new Criteria(), false));
        if (lastLocation != null) {
            lat = "" + lastLocation.getLatitude();
            lon = "" + lastLocation.getLongitude();
            locDataAge = "" + (System.currentTimeMillis() - lastLocation.getTime());
            locDataPrecision = "" + lastLocation.getAccuracy();
        }
    } else {
        Clog.w(Clog.baseLogTag, Clog.getString(R.string.permissions_missing_location));
    }

    // Do we have permission ACCESS_NETWORK_STATE?
    if (context.checkCallingOrSelfPermission(
            "android.permission.ACCESS_NETWORK_STATE") != PackageManager.PERMISSION_GRANTED) {
        Clog.e(Clog.baseLogTag, Clog.getString(R.string.permissions_missing_network_state));
        fail();
        this.cancel(true);
        return;
    }

    // Get orientation, the current rotation of the device
    orientation = context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE
            ? "h"
            : "v";
    // Get hidmd5, hidsha1, the device ID hashed
    if (Settings.getSettings().hidmd5 == null) {
        Settings.getSettings().hidmd5 = HashingFunctions.md5(aid);
    }
    hidmd5 = Settings.getSettings().hidmd5;
    if (Settings.getSettings().hidsha1 == null) {
        Settings.getSettings().hidsha1 = HashingFunctions.sha1(aid);
    }
    hidsha1 = Settings.getSettings().hidsha1;
    // Get devMake, devModel, the Make and Model of the current device
    devMake = Settings.getSettings().deviceMake;
    devModel = Settings.getSettings().deviceModel;
    // Get carrier
    if (Settings.getSettings().carrierName == null) {
        Settings.getSettings().carrierName = ((TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE)).getNetworkOperatorName();
    }
    carrier = Settings.getSettings().carrierName;
    // Get firstlaunch and convert it to a string
    firstlaunch = Settings.getSettings().first_launch;
    // Get ua, the user agent...
    ua = Settings.getSettings().ua;
    // Get wxh

    if (owner.isBanner()) {
        this.width = ((BannerAdView) owner).getAdWidth();
        this.height = ((BannerAdView) owner).getAdHeight();
    }

    maxHeight = owner.getContainerHeight();
    maxWidth = owner.getContainerWidth();

    if (Settings.getSettings().mcc == null || Settings.getSettings().mnc == null) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String networkOperator = tm.getNetworkOperator();
        if (networkOperator != null && networkOperator.length() >= 6) {
            Settings.getSettings().mcc = networkOperator.substring(0, 3);
            Settings.getSettings().mnc = networkOperator.substring(3);
        }
    }
    mcc = Settings.getSettings().mcc;
    mnc = Settings.getSettings().mnc;

    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    connection_type = wifi.isConnected() ? "wifi" : "wan";
    dev_time = "" + System.currentTimeMillis();

    if (owner instanceof InterstitialAdView) {
        // Make string for allowed_sizes
        allowedSizes = "";
        ArrayList<Size> sizes = ((InterstitialAdView) owner).getAllowedSizes();
        for (Size s : sizes) {
            allowedSizes += "" + s.width() + "x" + s.height();
            // If not last size, add a comma
            if (sizes.indexOf(s) != sizes.size() - 1)
                allowedSizes += ",";
        }
    }

    nativeBrowser = owner.getOpensNativeBrowser() ? "1" : "0";

    //Reserve price
    reserve = owner.getReserve();
    if (reserve <= 0) {
        this.psa = owner.shouldServePSAs ? "1" : "0";
    } else {
        this.psa = "0";
    }

    age = owner.getAge();
    if (owner.getGender() != null) {
        if (owner.getGender() == AdView.GENDER.MALE) {
            gender = "m";
        } else if (owner.getGender() == AdView.GENDER.FEMALE) {
            gender = "f";
        } else {
            gender = null;
        }
    }
    customKeywords = owner.getCustomKeywords();

    mcc = Settings.getSettings().mcc;
    mnc = Settings.getSettings().mnc;
    language = Settings.getSettings().language;
}

From source file:com.chalmers.schmaps.GoogleMapSearchLocation.java

/**
 *  method is called from onCreate() and it initiates the variables
 *  used in GoogleMapSearchLocation/*from   ww  w  .j av a 2s  . co  m*/
 */
private void assignInstances() {
    setContentView(R.layout.activity_map);
    //Fields used only once.
    Button editButton, directionsButton;
    Criteria criteria;
    String bestProvider;
    Drawable room, student;

    mapView = (MapView) findViewById(R.id.mapview);
    mapView.setBuiltInZoomControls(true);

    mapOverlays = mapView.getOverlays();
    room = this.getResources().getDrawable(R.drawable.dot);
    student = this.getResources().getDrawable(R.drawable.chalmersandroid);
    mapItemizedRoom = new MapItemizedOverlay(room, this);
    mapItemizedStudent = new MapItemizedOverlay(student, this);

    editButton = (Button) findViewById(R.id.edittextbutton);
    directionsButton = (Button) findViewById(R.id.directionbutton);
    lectureEdit = (EditText) findViewById(R.id.edittextlecture);
    editButton.setOnClickListener(this);
    directionsButton.setOnClickListener(this);

    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    //deafult criteria
    criteria = new Criteria();
    //best reception
    bestProvider = locationManager.getBestProvider(criteria, false);
    //gets last known location from chosen provider
    location = locationManager.getLastKnownLocation(bestProvider);

    roomSearched = false;
    running = false;

}

From source file:fr.matthiasbosc.translucentmap.MainActivity.java

public void getMap() {

    SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    String pref_map_type = SP.getString("map_type", MAP_TYPE);

    if ("MAP_TYPE_NORMAL".equals(pref_map_type)) {
        mapType = GoogleMap.MAP_TYPE_NORMAL;
    } else if ("MAP_TYPE_SATELLITE".equals(pref_map_type)) {
        mapType = GoogleMap.MAP_TYPE_SATELLITE;
    } else if ("MAP_TYPE_HYBRID".equals(pref_map_type)) {
        mapType = GoogleMap.MAP_TYPE_HYBRID;
    } else if ("MAP_TYPE_TERRAIN".equals(pref_map_type)) {
        mapType = GoogleMap.MAP_TYPE_TERRAIN;
    }/* w  ww  .j  a v a2 s  .  c om*/

    mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String provider = mLocationManager.getBestProvider(criteria, true);

    mLocation = mLocationManager.getLastKnownLocation(provider);
    if (mLocation == null) {
        Toast.makeText(this, R.string.location_unavailable, Toast.LENGTH_SHORT).show();
        latitude = 45.759723;
        longitude = 4.842223;
        latLng = new LatLng(latitude, longitude);
    } else {
        latitude = mLocation.getLatitude();
        longitude = mLocation.getLongitude();
        latLng = new LatLng(latitude, longitude);
    }

    if (mMap == null) {
        SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mMap = fragment.getMap();

        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(13));
        mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("Ma position"));
    }

    mMap.setMapType(mapType);
    setMapPadding();
    mMap.setMyLocationEnabled(true);
    mMap.setBuildingsEnabled(true);
    mMap.getUiSettings().setCompassEnabled(true);
    mMap.setTrafficEnabled(SP.getBoolean("traffic_layout", false));

    handleIntent(getIntent());
}

From source file:com.example.mohamed.a3qaqer.RegisterActvity.java

private void getloc() {
    if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        loc_string = "none";// indicate that no gps data
        return;/*  w w w  . j a  v a 2 s .c  om*/
    }
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setBearingRequired(true);
    criteria.setCostAllowed(true);
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    criteria.setAltitudeRequired(false);
    String bestProvider = locationManager.getBestProvider(criteria, true);
    if (ActivityCompat.checkSelfPermission(this,
            android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this,
                    android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    locationManager.requestLocationUpdates(bestProvider, 2000, 10, new LocationListener() {
        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {
        }

        @Override
        public void onProviderEnabled(String s) {
        }

        @Override
        public void onProviderDisabled(String s) {
        }

        @Override
        public void onLocationChanged(final Location location) {
        }
    });
    Location myLocation = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
    double longitude = myLocation.getLongitude();
    double latitude = myLocation.getLatitude();
    loc_string = latitude + "-" + longitude;

}