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:it.ms.theing.loquitur.functions.LocationInterface.java

private Location getLocation() {
    done = true;// w w w.  ja va2  s.c  om
    long timeInMillis = Calendar.getInstance().getTimeInMillis();
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    String fine = locationManager.getBestProvider(criteria, true);
    if (fine == null)
        return null;
    Location location = locationManager.getLastKnownLocation(fine);
    if (location != null) {
        if (timeInMillis - location.getTime() < TIMEVAL) {
            return location;
        }
    }
    criteria.setAccuracy(Criteria.ACCURACY_COARSE);
    String coarse = locationManager.getBestProvider(criteria, true);
    if (!(fine.equals(coarse))) {
        location = locationManager.getLastKnownLocation(fine);
        if (location != null) {
            if (timeInMillis - location.getTime() < TIMEVAL) {
                return location;
            }
        }
    }
    timeout.postDelayed(tout, TIMEOUT); // At most 1 minute
    //locationManager.requestSingleUpdate(fine, ll, Looper.myLooper());
    locationManager.requestSingleUpdate(fine, ll, null);
    done = false;
    return null;
}

From source file:com.nearnotes.NoteLocation.java

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Use the Builder class for convenient dialog construction
    Bundle extras = getArguments();/*  w  w  w . j  av a2  s  .c o m*/
    mTypeFrag = extras.getInt("TypeFrag");

    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity());
    Boolean gpsPref = sharedPref.getBoolean("pref_key_ignore_gps", false);
    mLocationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
    mCriteria = new Criteria();
    if (gpsPref) {
        mCriteria.setPowerRequirement(Criteria.POWER_HIGH);
    } else
        mCriteria.setPowerRequirement(Criteria.POWER_MEDIUM);
    mProvider = mLocationManager.getBestProvider(mCriteria, true);
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    boolean oldApi = false;
    int locationMode = 4;
    Log.e("mProvider", mProvider);

    ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    boolean networkAvailable = true;

    TelephonyManager tm = (TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE);
    boolean networkType = true;
    if (tm.getNetworkType() == TelephonyManager.NETWORK_TYPE_UNKNOWN && !networkInfo.isConnected()) {
        networkType = false;
    }

    Log.d("Phone state before if statement", "Phone State: " + mServiceState);
    Log.e("network isavailable", String.valueOf(networkInfo.isAvailable()));
    if (!networkType || !mLocationManager.isProviderEnabled("network")) {
        networkAvailable = false;
    }

    try {
        Log.e("Location_mode", String.valueOf(
                Settings.Secure.getInt(getActivity().getContentResolver(), Settings.Secure.LOCATION_MODE)));
        locationMode = Settings.Secure.getInt(getActivity().getContentResolver(),
                Settings.Secure.LOCATION_MODE);
    } catch (SettingNotFoundException e) {
        oldApi = true;
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    if ((oldApi && mProvider.matches("passive")) || locationMode == LOCATION_MODE_OFF || (!networkAvailable
            && (mProvider.matches("network") || (!gpsPref && mProvider.matches("gps"))))) {
        builder.setTitle(getString(R.string.dialog_location_no_location_services_title));
        builder.setMessage(getString(R.string.dialog_location_no_location_services_message));
        builder.setNeutralButton(R.string.dialog_location_button_settings, noNetworkButton);
        mAbortRequest = true;
    } else if ((oldApi && mProvider.matches("gps") && gpsPref) || (mProvider.matches("gps") && gpsPref
            && (locationMode == LOCATION_MODE_SENSORS_ONLY || locationMode == LOCATION_MODE_HIGH_ACCURACY))) {
        if (mTypeFrag == NOTE_EDIT) {
            builder.setTitle(getString(R.string.dialog_location_finding_note_gps));
        } else if (mTypeFrag == NOTE_LIST) {
            builder.setTitle(getString(R.string.dialog_location_updating_note_gps));
        }
        if (locationMode == LOCATION_MODE_SENSORS_ONLY || (oldApi && mProvider.matches("gps"))
                || !networkAvailable) {
            builder.setMessage(getString(R.string.dialog_location_only_gps_message));
            builder.setNeutralButton(R.string.dialog_location_button_settings, noNetworkButton);

        } else
            builder.setPositiveButton(R.string.dialog_location_use_network, null);

        builder.setView(getActivity().getLayoutInflater().inflate(R.layout.dialogue_location, null));

    } else if ((oldApi && mProvider.matches("network")) || (mProvider.matches("network")
            && (locationMode == LOCATION_MODE_BATTERY_SAVING || locationMode == LOCATION_MODE_HIGH_ACCURACY))) {
        builder.setView(getActivity().getLayoutInflater().inflate(R.layout.dialogue_location, null));
        if (mTypeFrag == NOTE_EDIT) {
            builder.setTitle(getString(R.string.dialog_location_finding_note_network));
        } else if (mTypeFrag == NOTE_LIST) {
            builder.setTitle(getString(R.string.dialog_location_updating_note_network));
        }

    }
    builder.setNegativeButton(R.string.cancel, cancelListener);
    // Create the AlertDialog object and return it

    // builder.create();

    builder.setOnKeyListener(new DialogInterface.OnKeyListener() {

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

            return false;
        }
    });

    mRealDialog = builder.create();
    // final LocationListener getFragment() = this.;

    mRealDialog.setOnShowListener(usingNetwork);
    mRealDialog.setCanceledOnTouchOutside(false);
    // mRealDialog.setCancelable(false);
    return mRealDialog;

}

From source file:com.example.getneighborposition.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    textview = (TextView) findViewById(R.id.tv_location);

    // Google Play Services???????
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

    // Showing status
    if (status != ConnectionResult.SUCCESS) {
        // Google Play Services ?????
        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
        dialog.show();//from w  w  w .  j a va 2 s.  c  o m

    } else {
        // Google Play Services ???
        // activity_main.xml?SupportMapFragment????
        SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

        // fragment?GoogleMap object?
        gMap = fm.getMap();

        // Google Map?MyLocation???
        gMap.setMyLocationEnabled(true);
        gMap.setIndoorEnabled(true);
        gMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        gMap.setTrafficEnabled(true);

        // ?LOCATION_SERVICE?LocationManager object?
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        // retrieve provider?criteria object?
        Criteria criteria = new Criteria();

        // Best provider?????
        String provider = locationManager.getBestProvider(criteria, true);

        //provider??????????????
        if (provider != null) {
            Toast.makeText(this, provider + "???", Toast.LENGTH_LONG).show();

            Log.d("app", "the best provider is " + provider);
            // ???
            Location location = locationManager.getLastKnownLocation(provider);

            if (location != null) {
                onLocationChanged(location);
            }
            locationManager.requestLocationUpdates(provider, 20000, 0, this);
        } else { //GPS?????????
            Toast.makeText(this, "????????", Toast.LENGTH_LONG).show();
        }
    }

}

From source file:com.example.aximcore.hangyamaps.MapsActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    setUpMapIfNeeded();/*www .j av a  2 s  .co m*/

    // Begin ****************************************
    if (mMap != null) {
        mMap.setMyLocationEnabled(true); // sajt lokalizci engedlyezse
    }

    latituteField = (TextView) findViewById(R.id.TextView01); // szllesgi
    longitudeField = (TextView) findViewById(R.id.TextView02); // hosszsgi
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // rendszerszolgltatsok lekrse
    Criteria criteria = new Criteria();
    provider = locationManager.getBestProvider(criteria, false); // legjobb szolgltats lekrse ( jelen esetben GPS )
    Location location = locationManager.getLastKnownLocation(provider); // utols ismert helyzetnk

    if (location != null) {
        System.out.println("Provider " + provider + " kivlasztva.");
        onLocationChanged(location); // ha helyzetnk megvltozna
    } else {
        latituteField.setText("Hely nem elrhet!");
        longitudeField.setText("Hely nem elrhet");
    }
    // End ******************************************
}

From source file:com.swetha.easypark.GoogleDirectionsActivity.java

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mapdirections);
    StrictMode.setThreadPolicy(/*from w w  w.  j  a  v a2 s.  c o  m*/
            new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork() // StrictMode is most commonly used to catch accidental disk or network access on the application's main thread
                    .penaltyLog().build());
    Log.i("GoogleDirectionsActivity", "Inside Oncreate");

    Intent theIntent = getIntent();
    tolat = theIntent.getDoubleExtra(GetParkingLots.LATITUDE, Constants.doubleDefaultValue);
    tolng = theIntent.getDoubleExtra(GetParkingLots.LONGITUDE, Constants.doubleDefaultValue);

    toPosition = new LatLng(tolat, tolng);

    Log.i("GoogleDirectionsActivity",
            "After Setting tolat, tolng, toPosition" + tolat + "\n" + tolng + "\n" + toPosition);

    md = new GetDirections();
    Log.i("GoogleDirectionsActivity", "After calling GetDirctions constructor");

    FragmentManager fm = getSupportFragmentManager();
    Log.i("GoogleDirectionsActivity", "After creating fragmentManager" + fm);
    SupportMapFragment supportMapfragment = ((SupportMapFragment) fm.findFragmentById(R.id.drivingdirections));

    Log.i("GoogleDirectionsActivity", "After creating SupportMapFragment" + supportMapfragment);
    mMap = supportMapfragment.getMap();
    Log.i("GoogleDirectionsActivity", "After getting map");

    mMap.setMyLocationEnabled(true);
    Log.i("GoogleDirectionsActivity", "After  setMyLocationEnabled");
    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    Log.i("GoogleDirectionsActivity", "After  locationManager");
    Criteria criteria = new Criteria();

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

    if (provider != null && !provider.equals("")) {

        // Get the location from the given provider 
        location = locationManager.getLastKnownLocation(provider);

        locationManager.requestLocationUpdates(provider, 500, 1, GoogleDirectionsActivity.this);

        if (location != null) {

            fromlat = location.getLatitude();
            fromlng = location.getLongitude();
        }

        else {
            fromlat = GetParkingLots.latitude;
            fromlng = GetParkingLots.longitude;
        }

    } else {
        Toast.makeText(getBaseContext(), "No Provider Found", Toast.LENGTH_SHORT).show();
        finish();
    }
    Log.e("GoogleDirectionsActivity", "After  setting location");
    fromPosition = new LatLng(fromlat, fromlng);
    LatLng coordinates = new LatLng(fromlat, fromlng);
    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 16));

    mMap.addMarker(new MarkerOptions().position(fromPosition).title("Start"));
    mMap.addMarker(new MarkerOptions().position(toPosition).title("End"));

    Document doc = md.getDocument(fromPosition, toPosition, Constants.MODE_DRIVING);
    String duration = md.getDurationText(doc);

    tv_duration = (TextView) findViewById(R.id.tv_time);
    tv_duration.setText("Estimated driving time:" + duration);

    ArrayList<LatLng> directionPoint = md.getDirection(doc);

    PolylineOptions rectLine = new PolylineOptions().width(6).color(Color.RED);

    for (int i = 0; i < directionPoint.size(); i++) {
        rectLine.add(directionPoint.get(i));
    }

    mMap.addPolyline(rectLine);
}

From source file:mx.itchetumal.sensado_urbano.MainMapas.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void setUpMap() {
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
    if (status != ConnectionResult.SUCCESS) {
        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
        dialog.show();// ww  w .  j av a 2s .c  o m
    } else {

        if (map == null) {
            map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
            if (map != null) {
                map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                map.setMyLocationEnabled(true);
            }
        }
        lo = (LocationManager) getSystemService(LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String provider = lo.getBestProvider(criteria, true);
        myLoc = lo.getLastKnownLocation(provider);
        if (myLoc != null) {
            onLocationChanged(myLoc);
        }
        lo.requestLocationUpdates(provider, 20000, 0, this);

        FragmentManager myfrag = getFragmentManager();
        MapFragment myFragment = (MapFragment) myfrag.findFragmentById(R.id.map);
        map = myFragment.getMap();
        map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        map.setMyLocationEnabled(true);
        //   map.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(myLoc.getLatitude(), myLoc.getLongitude())));
        map.setOnMapClickListener(this);
        map.setOnMapLongClickListener(this);
        map.setOnMarkerClickListener(this);
        marketClicked = false;
    }
}

From source file:com.refujiate.ui.MainMapaActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.tab_ubicacion);
    // Getting Google Play availability status
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

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

        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
        dialog.show();//from www  . j a  va  2s .c  om

    } else { // Google Play Services are available

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

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

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

        googleMap.moveCamera(
                CameraUpdateFactory.newLatLngZoom(new LatLng(-8.105972881341886, -79.028778076171880), 12));

        // Getting LocationManager object from System Service LOCATION_SERVICE
        LocationManager locationManager = (LocationManager) getSystemService(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);
    }
    addMaker(0);
    Intent svc = new Intent(this, RefugiateService.class);
    startService(svc);
}

From source file:com.facebook.android.Places.java

public void getLocation() {
    /*//w w w .  j  av a 2 s.  c  o m
     * launch a new Thread to get new location
     */
    new Thread() {
        @Override
        public void run() {
            Looper.prepare();
            dialog = ProgressDialog.show(Places.this, "", getString(R.string.fetching_location), false, true,
                    new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            showToast("No location fetched.");
                        }
                    });

            if (lm == null) {
                lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            }

            if (locationListener == null) {
                locationListener = new MyLocationListener();
            }

            Criteria criteria = new Criteria();
            criteria.setAccuracy(Criteria.ACCURACY_COARSE);
            String provider = lm.getBestProvider(criteria, true);
            if (provider != null && lm.isProviderEnabled(provider)) {
                lm.requestLocationUpdates(provider, 1, 0, locationListener, Looper.getMainLooper());
            } else {
                /*
                 * GPS not enabled, prompt user to enable GPS in the
                 * Location menu
                 */
                new AlertDialog.Builder(Places.this).setTitle(R.string.enable_gps_title)
                        .setMessage(getString(R.string.enable_gps))
                        .setPositiveButton(R.string.gps_settings, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                startActivityForResult(
                                        new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),
                                        0);
                            }
                        }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                Places.this.finish();
                            }
                        }).show();
            }
            Looper.loop();
        }
    }.start();
}

From source file:ch.hesso.master.sweetcity.activity.report.ReportActivity.java

void updateCurrentLocation() {
    if (this.locationListener == null)
        this.locationListener = new LocationListener() {
            @Override//from  w w  w . jav a 2s  .  c om
            public void onLocationChanged(Location location) {
                ReportActivity.this.currentLocation = location;
            }

            @Override
            public void onProviderDisabled(String provider) {
            }

            @Override
            public void onProviderEnabled(String provider) {
            }

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

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

    LocationManager locationManager = (LocationManager) ReportActivity.this.getSystemService(LOCATION_SERVICE);
    locationManager.requestSingleUpdate(criteria, this.locationListener, null);
}

From source file:de.avanux.android.livetracker2.LocationTracker.java

public String getGpsProvider() {
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);/*  w  ww .  ja  v  a2 s. c o  m*/
    criteria.setCostAllowed(false);
    // criteria.setPowerRequirement(Criteria.POWER_LOW);
    criteria.setSpeedRequired(true);

    return getLocationManager().getBestProvider(criteria, true);
}