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.njlabs.amrita.aid.about.Amrita.java

public void directions_cbe(View view) {
    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String bestProvider = locationManager.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;/*from  ww  w  .j  a  va  2 s.c o  m*/
    }

    LocationListener loc_listener = new LocationListener() {
        public void onLocationChanged(Location l) {
        }

        public void onProviderEnabled(String p) {
        }

        public void onProviderDisabled(String p) {
        }

        public void onStatusChanged(String p, int status, Bundle extras) {
        }
    };
    locationManager.requestLocationUpdates(bestProvider, 0, 0, loc_listener);
    Location location = locationManager.getLastKnownLocation(bestProvider);

    double lat;
    double lon;
    try {
        lat = location.getLatitude();
        lon = location.getLongitude();
    } catch (NullPointerException e) {
        lat = -1.0;
        lon = -1.0;
    }
    Uri uri = Uri.parse(
            "http://maps.google.com/maps?f=d&saddr=" + lat + "," + lon + "&daddr=10.900539,76.902806&hl=en");
    Intent it = new Intent(Intent.ACTION_VIEW, uri);
    startActivity(it);

}

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

@Override
protected void onCreate(Bundle savedInstanceState) {

    if (!isGooglePlayServicesAvailable()) {
        finish();//from www  . j a va 2 s . com
    }
    super.onCreate(savedInstanceState);
    setContentView(R.layout.getparkinglots);

    SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    googleMap = supportMapFragment.getMap();

    googleMap.setMyLocationEnabled(true);
    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

    if (gps_enabled) {
        Criteria criteria = new Criteria();

        provider = locationManager.getBestProvider(criteria, true);

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

            locationManager.requestLocationUpdates(provider, 500, 1, GetParkingLots.this);
            // Get the location from the given provider 
            location = locationManager.getLastKnownLocation(provider);

        }
    }
    Log.i("GetParkingLots", "Value of network_enabled and location" + network_enabled + location);
    if (location == null && network_enabled) {

        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 500, 1, GetParkingLots.this);

    }

    if (location == null && !network_enabled && !gps_enabled) {
        Toast.makeText(getBaseContext(), "Enable your location services", Toast.LENGTH_LONG).show();
    }
    if (location != null)
        onLocationChanged(location);
    else {

        Toast.makeText(getBaseContext(), "Location can't be retrieved", Toast.LENGTH_SHORT).show();
    }

    tv_fromTime = (TextView) findViewById(R.id.tv_fromTime);
    fromTimeString = Constants.dtf.format(new Date()).toString();
    tv_fromTime.setText(fromTimeString);
    long lval = DateTimeHelpers.convertToLongFromTime(Constants.dtf.format(new Date()).toString());
    Log.i("GetParkingLots",
            "The value of current time:" + Constants.dtf.format(new Date()).toString() + "in long is" + lval);
    Log.i("GetParkingLots",
            "The value of current time:" + lval + "in long is" + DateTimeHelpers.convertToTimeFromLong(lval));
    tv_toTime = (TextView) findViewById(R.id.tv_ToTime);
    // Parsing the date
    toTimeString = Constants.dtf.format(new Date()).toString();
    tv_toTime.setText(toTimeString);

    btnFromTime = (Button) findViewById(R.id.fromButton);
    btnFromTime.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

            // Create the dialog
            final Dialog mDateTimeDialog = new Dialog(GetParkingLots.this);
            // Inflate the root layout
            final RelativeLayout mDateTimeDialogView = (RelativeLayout) getLayoutInflater()
                    .inflate(R.layout.date_time_dialog, null);
            // Grab widget instance
            mDateTimePicker = (DateTimePicker) mDateTimeDialogView.findViewById(R.id.DateTimePicker);
            mDateTimePicker.setDateChangedListener(GetParkingLots.this);

            // Update demo TextViews when the "OK" button is clicked 
            ((Button) mDateTimeDialogView.findViewById(R.id.SetDateTime))
                    .setOnClickListener(new OnClickListener() {
                        Calendar cal;

                        @SuppressWarnings("deprecation")
                        public void onClick(View v) {
                            mDateTimePicker.clearFocus();
                            try {
                                cal = new GregorianCalendar(mDateTimePicker.getYear(),
                                        Integer.parseInt(mDateTimePicker.getMonth()), mDateTimePicker.getDay(),
                                        mDateTimePicker.getHour(), mDateTimePicker.getMinute());
                                fromTimeString = DateTimeHelpers.dtf.format(cal.getTime());
                                tv_fromTime.setText(fromTimeString);
                            } catch (Exception e) {
                                final AlertDialog alertDialog = new AlertDialog.Builder(GetParkingLots.this)
                                        .create();

                                alertDialog.setMessage("Enter a valid date");

                                alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {

                                        alertDialog.dismiss();
                                    }
                                });

                                alertDialog.show();
                            }

                            mDateTimeDialog.dismiss();
                        }
                    });

            // Cancel the dialog when the "Cancel" button is clicked
            ((Button) mDateTimeDialogView.findViewById(R.id.CancelDialog))
                    .setOnClickListener(new OnClickListener() {

                        public void onClick(View v) {
                            // TODO Auto-generated method stub
                            mDateTimeDialog.cancel();
                        }
                    });

            // Reset Date and Time pickers when the "Reset" button is clicked

            ((Button) mDateTimeDialogView.findViewById(R.id.ResetDateTime))
                    .setOnClickListener(new OnClickListener() {

                        public void onClick(View v) {
                            // TODO Auto-generated method stub
                            mDateTimePicker.reset();
                        }
                    });

            // Setup TimePicker
            // No title on the dialog window
            mDateTimeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            // Set the dialog content view
            mDateTimeDialog.setContentView(mDateTimeDialogView);
            // Display the dialog
            mDateTimeDialog.show();

        }
    });

    btnToTime = (Button) findViewById(R.id.toButton);
    btnToTime.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

            // Create the dialog
            final Dialog mDateTimeDialog = new Dialog(GetParkingLots.this);
            // Inflate the root layout
            final RelativeLayout mDateTimeDialogView = (RelativeLayout) getLayoutInflater()
                    .inflate(R.layout.date_time_dialog, null);
            // Grab widget instance
            final DateTimePicker mDateTimePicker = (DateTimePicker) mDateTimeDialogView
                    .findViewById(R.id.DateTimePicker);
            mDateTimePicker.setDateChangedListener(GetParkingLots.this);

            // Update demo TextViews when the "OK" button is clicked 
            ((Button) mDateTimeDialogView.findViewById(R.id.SetDateTime))
                    .setOnClickListener(new OnClickListener() {
                        Calendar cal;

                        @SuppressWarnings("deprecation")
                        public void onClick(View v) {
                            mDateTimePicker.clearFocus();

                            Log.i("toButton", "Value of ToString before cal" + toTimeString);
                            try {
                                cal = new GregorianCalendar(mDateTimePicker.getYear(),
                                        Integer.parseInt(mDateTimePicker.getMonth()), mDateTimePicker.getDay(),
                                        mDateTimePicker.getHour(), mDateTimePicker.getMinute());
                                toTimeString = DateTimeHelpers.dtf.format(cal.getTime());
                                Log.i("toButton", "Value of ToString before cal" + toTimeString);

                                tv_toTime.setText(toTimeString);

                            } catch (Exception e) // fixing the bug where the user doesnt enter anything in the textbox
                            {
                                final AlertDialog alertDialog = new AlertDialog.Builder(GetParkingLots.this)
                                        .create();

                                alertDialog.setMessage("Enter a valid date");
                                alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        alertDialog.dismiss();
                                    }
                                });

                                alertDialog.show();
                            }
                            //dateTimeTo = new DateTime(mDateTimePicker.getYear(), Integer.parseInt(mDateTimePicker.getMonth()) ,  mDateTimePicker.getDay(),  mDateTimePicker.getHour(),  mDateTimePicker.getMinute()); ;

                            mDateTimeDialog.dismiss();
                        }
                    });

            ((Button) mDateTimeDialogView.findViewById(R.id.CancelDialog))
                    .setOnClickListener(new OnClickListener() {

                        public void onClick(View v) {
                            // TODO Auto-generated method stub
                            mDateTimeDialog.cancel();
                        }
                    });

            // Reset Date and Time pickers when the "Reset" button is clicked

            ((Button) mDateTimeDialogView.findViewById(R.id.ResetDateTime))
                    .setOnClickListener(new OnClickListener() {

                        public void onClick(View v) {
                            // TODO Auto-generated method stub
                            mDateTimePicker.reset();
                        }
                    });

            // Setup TimePicker
            // No title on the dialog window
            mDateTimeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            // Set the dialog content view
            mDateTimeDialog.setContentView(mDateTimeDialogView);
            // Display the dialog
            mDateTimeDialog.show();

        }
    });

    btnGetParkingLots = (Button) findViewById(R.id.getNearByParkingLotsButton);
    btnGetParkingLots.setOnClickListener(new View.OnClickListener() {

        @SuppressWarnings("deprecation")
        public void onClick(View v) {
            et_search = (EditText) findViewById(R.id.edittextsearch);
            rg = (RadioGroup) findViewById(R.id.rg);
            checkedRbId = rg.getCheckedRadioButtonId();
            Log.i("LOG_TAG: GetParkingLots", "checked radiobutton id is" + checkedRbId);

            if (checkedRbId == R.id.rbradius) {
                isRadiusIndicator = true;
                radius = et_search.getText().toString();
            } else {
                isRadiusIndicator = false;
                zipcode = et_search.getText().toString();
            }

            final Intent intent = new Intent(GetParkingLots.this, DisplayVacantParkingLots.class);
            Log.i(TAG, "Inside getNearByParkingLots");
            Log.i(TAG, "Value of fromString" + fromTimeString);
            long lFromVal = DateTimeHelpers.convertToLongFromTime(fromTimeString);
            Log.i(TAG, "Value of ToString" + toTimeString);
            long lToVal = DateTimeHelpers.convertToLongFromTime(toTimeString);
            if ((lToVal - lFromVal) < Constants.thrityMinInMilliSeconds) {
                final AlertDialog alertDialog = new AlertDialog.Builder(GetParkingLots.this).create();

                alertDialog.setMessage("You have to park the car for at least 30 min");

                alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                        alertDialog.dismiss();
                    }
                });

                alertDialog.show();

            } else {
                intent.putExtra(LATITUDE, latitude);
                intent.putExtra(LONGITUDE, longitude);
                intent.putExtra(FROMTIME, lFromVal);
                intent.putExtra(TOTIME, lToVal);
                intent.putExtra(RadiusOrZIPCODE, isRadiusIndicator);
                if (isRadiusIndicator)
                    try {

                        intent.putExtra(RADIUS, Double.parseDouble(radius));
                        startActivity(intent);
                    } catch (Exception e) {
                        final AlertDialog alertDialog = new AlertDialog.Builder(GetParkingLots.this).create();

                        alertDialog.setMessage("Enter valid radius");

                        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {

                                alertDialog.dismiss();

                            }
                        });

                        alertDialog.show();
                    }
                else {
                    try {

                        intent.putExtra(ZIPCODE, Long.parseLong(zipcode));
                        startActivity(intent);
                    } catch (Exception e) {
                        final AlertDialog alertDialog = new AlertDialog.Builder(GetParkingLots.this).create();

                        alertDialog.setMessage("Enter a valid Zip code");

                        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                alertDialog.dismiss();

                            }
                        });

                        alertDialog.show();
                    }
                }

            }

        }
    });

}

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

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

    // Get Google Maps Setup
    final SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    final AppCompatActivity activity = (AppCompatActivity) getActivity();

    // Retrieve a refrence of the location manager on Android from the location service
    locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
    // Get the best location provider available from the location manager
    provider = locationManager.getBestProvider(new Criteria(), false);

    // Setting up the app action bar at the top
    final ActionBar supportActionBar = activity.getSupportActionBar();
    // Show the back arrow when user navigates to other screens than home
    supportActionBar.setDisplayHomeAsUpEnabled(true);
    supportActionBar.setTitle("Setting up...");

    // Grab the "Start Driving" image from the "res/drawable" folder
    // And create an image button using it
    startDriving = (ImageButton) view.findViewById(R.id.imageButton);
    // When user clicks on the button, run this function
    startDriving.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Log to the console
            Log.i("Button Clicked", "Start Driving");

            // If the user hasn't started driving
            if (!startedDriving) {
                supportActionBar.setTitle("Preparing for this trip...");

                // The UI thread solely deals with the user interface and can execute tasks on it
                API.runInAsyncUIThread(new Runnable() {
                    @Override/*from  w w w . ja v a  2  s  . c  om*/
                    public void run() {
                        if (startDrive(deviceID)) {
                            // Keep the screen Awake (do not lock automatically or dim)
                            // https://developer.android.com/training/scheduling/wakelock.html
                            AnalyzeMyDriving.this.getActivity().getWindow()
                                    .addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

                            reserveCar();

                            // Change the "Start Driving" to "End Driving"
                            startDriving.setImageResource(R.drawable.enddriving);

                            transmissionCount = 0;

                            supportActionBar.setTitle("Please start driving safely.");
                        } else {
                            // Show a toast to the user
                            Toast.makeText(activity.getApplicationContext(),
                                    "Failed to connect to IoT Platform.", Toast.LENGTH_SHORT).show();

                            supportActionBar.setTitle("Check server connection.");
                        }
                    }
                }, activity);
            } else {
                startedDriving = false;

                supportActionBar.setTitle("Completing the trip...");

                // The UI thread solely deals with the user interface and can execute tasks on it
                API.runInAsyncUIThread(new Runnable() {
                    @Override
                    public void run() {
                        // Complete the reservation on the server
                        completeReservation(reservationId[0], false);

                        // Change the button image back to "Start Driving"
                        startDriving.setImageResource(R.drawable.startdriving);

                        // No longer need to keep the screen awake
                        AnalyzeMyDriving.this.getActivity().getWindow()
                                .clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                    }
                }, activity);
            }
        }
    });

    this.view = view;
    return view;
}

From source file:jp.gr.java_conf.ya.shiobeforandroid3.UpdateTweetDrive.java

private final void init_location() {
    pref_app = PreferenceManager.getDefaultSharedPreferences(this);
    new Thread(new Runnable() {
        @Override/*from   ww  w.  j a v  a  2s .co  m*/
        public final void run() {
            try {
                final Criteria criteria = new Criteria();
                criteria.setAccuracy(Criteria.ACCURACY_FINE);
                criteria.setPowerRequirement(Criteria.POWER_HIGH);
                mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
                if (mLocationManager != null) {
                    // final String provider = manager.getBestProvider(criteria, true);
                    boolean provider_flag = false;
                    final List<String> providers = mLocationManager.getProviders(true);
                    for (final String provider : providers) {
                        if ((provider.equals(LocationManager.GPS_PROVIDER))
                                || (provider.equals(LocationManager.NETWORK_PROVIDER))) {
                            if (mLocationManager.isProviderEnabled(provider)) {
                                provider_flag = true;
                            }
                        }
                        WriteLog.write(UpdateTweetDrive.this, "requestLocationUpdates() provider: " + provider);

                        final int pref_locationinfo_mintime = ListAdapter.getPrefInt(UpdateTweetDrive.this,
                                "pref_locationinfo_mintime", "300000");
                        try {
                            new Runnable() {
                                @Override
                                public final void run() {
                                    if (ContextCompat.checkSelfPermission(UpdateTweetDrive.this,
                                            android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                                        mLocationManager.requestLocationUpdates(provider,
                                                pref_locationinfo_mintime, 0, UpdateTweetDrive.this);
                                    } else {
                                        if (Build.VERSION.SDK_INT >= 23)
                                            requestPermissions(
                                                    new String[] {
                                                            android.Manifest.permission.ACCESS_FINE_LOCATION },
                                                    REQUEST_PERMISSION);
                                    }
                                }
                            };
                        } catch (final Exception e) {
                            WriteLog.write(UpdateTweetDrive.this, e);
                        }
                    }

                    if (startup_flag == true) {
                        startup_flag = false;

                        if (provider_flag == false) {
                            toast(getString(R.string.open_location_source_settings));
                            try {
                                startActivity(new Intent("android.settings.LOCATION_SOURCE_SETTINGS"));
                            } catch (final ActivityNotFoundException e) {
                                WriteLog.write(UpdateTweetDrive.this, e);
                            } catch (final Exception e) {
                                WriteLog.write(UpdateTweetDrive.this, e);
                            }
                        }
                    }
                }
            } catch (final IllegalArgumentException e) {
                WriteLog.write(UpdateTweetDrive.this, e);
            } catch (final RuntimeException e) {
                WriteLog.write(UpdateTweetDrive.this, e);
            }

        }
    }).start();
}

From source file:com.jeremy.tripcord.main.TripcordFragment.java

private CameraUpdate getLastKnownLocation() {
    LocationManager lm = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_LOW);
    String provider = lm.getBestProvider(criteria, true);
    if (provider == null) {
        return null;
    }/*from ww  w.ja v a2  s. co m*/
    Location loc = lm.getLastKnownLocation(provider);
    if (loc != null) {
        return CameraUpdateFactory.newCameraPosition(
                CameraPosition.fromLatLngZoom(new LatLng(loc.getLatitude(), loc.getLongitude()), 14.0f));
    }
    return null;
}

From source file:com.oonusave.coupon.MyMapStore.java

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
    setContentView(R.layout.store_map_view);
    getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.my_title);
    mActivity = this;
    settings = getSharedPreferences(PREFS_NAME, 0);

    backButton = (ImageButton) findViewById(R.id.btnLeft);
    backButton.setVisibility(ImageButton.INVISIBLE);
    //backButton.setBackgroundResource(R.drawable.back_button);
    backButton.setBackgroundResource(ImageUtils.getBackIamge());
    backButton.setOnClickListener(this);

    titleBarTextView = (TextView) findViewById(R.id.titleBarTextView);
    titleBarTextView.setText(TitleTextUtils.getMapViewTitleText());
    ((ImageButton) findViewById(R.id.btnRight)).setVisibility(ImageButton.INVISIBLE);
    //      mapView = (MapView) findViewById(R.id.mapview);
    //      mapView.setBuiltInZoomControls(true);
    //      mapOverlays = mapView.getOverlays();

    // first overlay
    //      drawable = getResources().getDrawable(R.drawable.map);
    //      itemizedOverlay = new MyItemizedOverlay(drawable, mapView,true);
    ////from   w ww .  j  av  a 2s.co  m
    //
    //      //mapOverlays.add(itemizedOverlay);
    //      drawable2 = getResources().getDrawable(R.drawable.marker2);
    //      itemizedOverlay2 = new MyItemizedOverlay(drawable2, mapView,false);
    //      GeoPoint point2 = new GeoPoint((int)(Double.parseDouble(DataUtil.locationInfo.getLatitude()) * 1E6 ), (int)(Double.parseDouble(DataUtil.locationInfo.getLongitude()) * 1E6));
    //      OverlayItem overlayItem4 = new OverlayItem(point2, "Current Location", 
    //            "");      
    //      itemizedOverlay2.addOverlay(overlayItem4);

    //      mapOverlays.add(itemizedOverlay2);
    //
    //
    //      final MapController mc = mapView.getController();
    //      mc.animateTo(point2);
    //      mc.setZoom(9);
    //
    //      DataUtil.mapScreen = true;
    //      loadStores();

    // Get the location manager
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    // Define the criteria how to select the locatioin provider -> use
    // default
    Criteria criteria = new Criteria();
    Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

    // Initialize the location fields
    if (location != null) {
        System.out.println("Provider " + provider + " has been selected.");
        processOnLocationChanged(location);
    } else {
        //         latituteField.setText("Location not available");
        //         longitudeField.setText("Location not available");
    }
}

From source file:com.rareventure.gps2.reviewer.map.OsmMapGpsTrailerReviewerMapActivity.java

public void setupLocationUpdates(GpsLocationOverlay gpsLocationOverlay) {
    //the user may have disabled us from reading location data
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        Criteria criteria = new Criteria();
        criteria.setSpeedRequired(false);
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(false);/*from   w w  w .  ja va  2  s. c  om*/

        String locationProviderName = locationManager.getBestProvider(criteria, true);
        locationManager.requestLocationUpdates(locationProviderName, 0, 0, gpsLocationOverlay, getMainLooper());
    }
}

From source file:com.example.snapcacheexample.PickerActivity.java

@Override
protected void onStart() {
    super.onStart();
    if (FRIEND_PICKER.equals(getIntent().getData())) {
        try {//from  ww w . ja  va2 s. 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);
            if (bestProvider != null) {
                location = locationManager.getLastKnownLocation(bestProvider);
                if (locationManager.isProviderEnabled(bestProvider) && locationListener == null) {
                    locationListener = new LocationListener() {
                        @Override
                        public void onLocationChanged(Location location) {
                            float distance = location.distanceTo(placePickerFragment.getLocation());
                            if (distance >= LOCATION_CHANGE_THRESHOLD) {
                                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 = SAN_FRANCISCO_LOCATION;
                }
            }
            if (location != null) {
                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:org.navitproject.navit.NavitVehicle.java

/**
 * @brief Creates a new {@code NavitVehicle}
 *
 * @param context//from   w w w.ja  v a  2 s. com
 * @param pcbid The address of the position callback function called when a location update is received
 * @param scbid The address of the status callback function called when a status update is received
 * @param fcbid The address of the fix callback function called when a
 * {@code android.location.GPS_FIX_CHANGE} is received, indicating a change in GPS fix status
 */
NavitVehicle(Context context, int pcbid, int scbid, int fcbid) {
    if (ContextCompat.checkSelfPermission(context,
            android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // Permission is not granted
        return;
    }
    this.context = context;
    sLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    preciseLocationListener = new NavitLocationListener();
    preciseLocationListener.precise = true;
    fastLocationListener = new NavitLocationListener();

    /* Use 2 LocationProviders, one precise (usually GPS), and one
       not so precise, but possible faster. The fast provider is
       disabled when the precise provider gets its first fix. */

    // Selection criteria for the precise provider
    Criteria highCriteria = new Criteria();
    highCriteria.setAccuracy(Criteria.ACCURACY_FINE);
    highCriteria.setAltitudeRequired(true);
    highCriteria.setBearingRequired(true);
    highCriteria.setCostAllowed(true);
    highCriteria.setPowerRequirement(Criteria.POWER_HIGH);

    // Selection criteria for the fast provider
    Criteria lowCriteria = new Criteria();
    lowCriteria.setAccuracy(Criteria.ACCURACY_COARSE);
    lowCriteria.setAltitudeRequired(false);
    lowCriteria.setBearingRequired(false);
    lowCriteria.setCostAllowed(true);
    lowCriteria.setPowerRequirement(Criteria.POWER_HIGH);

    Log.e("NavitVehicle", "Providers " + sLocationManager.getAllProviders());

    preciseProvider = sLocationManager.getBestProvider(highCriteria, false);
    Log.e("NavitVehicle", "Precise Provider " + preciseProvider);
    fastProvider = sLocationManager.getBestProvider(lowCriteria, false);
    Log.e("NavitVehicle", "Fast Provider " + fastProvider);
    vehicle_pcbid = pcbid;
    vehicle_scbid = scbid;
    vehicle_fcbid = fcbid;

    context.registerReceiver(preciseLocationListener, new IntentFilter(GPS_FIX_CHANGE));
    sLocationManager.requestLocationUpdates(preciseProvider, 0, 0, preciseLocationListener);
    sLocationManager.addGpsStatusListener(preciseLocationListener);

    /*
     * Since Android criteria have no way to specify "fast fix", lowCriteria may return the same
     * provider as highCriteria, even if others are available. In this case, do not register two
     * listeners for the same provider but pick the fast provider manually. (Usually there will
     * only be two providers in total, which makes the choice easy.)
     */
    if (fastProvider == null || preciseProvider.compareTo(fastProvider) == 0) {
        List<String> fastProviderList = sLocationManager.getProviders(lowCriteria, false);
        fastProvider = null;
        for (String fastCandidate : fastProviderList) {
            if (preciseProvider.compareTo(fastCandidate) != 0) {
                fastProvider = fastCandidate;
                break;
            }
        }
    }
    if (fastProvider != null) {
        sLocationManager.requestLocationUpdates(fastProvider, 0, 0, fastLocationListener);
    }
}

From source file:net.freifunk.android.discover.Main.java

private LatLng getLocation() {
    // 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();/*  w  w w.j a  v  a 2  s .  c  o  m*/

    } else { // Google Play Services are available

        // 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);
        return new LatLng(location.getLatitude(), location.getLongitude());
    }
    return new LatLng(0, 0);
}