Example usage for android.location LocationManager getLastKnownLocation

List of usage examples for android.location LocationManager getLastKnownLocation

Introduction

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

Prototype

@RequiresPermission(anyOf = { ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION })
public Location getLastKnownLocation(String provider) 

Source Link

Document

Returns a Location indicating the data from the last known location fix obtained from the given provider.

Usage

From source file:nl.sogeti.android.gpstracker.viewer.LoggerMap.java

/**
 * Get the last know position from the GPS provider and return that
 * information wrapped in a GeoPoint to which the Map can navigate.
 *
 * @return/*  w  ww.j  a v  a 2s . c o m*/
 * @see GeoPoint
 */
private GeoPoint getLastKnowGeopointLocation() {
    int microLatitude = 0;
    int microLongitude = 0;
    LocationManager locationManager = (LocationManager) this.getApplication()
            .getSystemService(Context.LOCATION_SERVICE);
    Location locationFine = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if (locationFine != null) {
        microLatitude = (int) (locationFine.getLatitude() * 1E6d);
        microLongitude = (int) (locationFine.getLongitude() * 1E6d);
    }
    if (locationFine == null || microLatitude == 0 || microLongitude == 0) {
        Location locationCoarse = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        if (locationCoarse != null) {
            microLatitude = (int) (locationCoarse.getLatitude() * 1E6d);
            microLongitude = (int) (locationCoarse.getLongitude() * 1E6d);
        }
        if (locationCoarse == null || microLatitude == 0 || microLongitude == 0) {
            microLatitude = 51985105;
            microLongitude = 5106132;
        }
    }
    GeoPoint geoPoint = new GeoPoint(microLatitude, microLongitude);
    return geoPoint;
}

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

@Override
protected void onCreate(Bundle savedInstanceState) {

    if (!isGooglePlayServicesAvailable()) {
        finish();//from  w w w. j a  va2  s.c  o m
    }
    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:net.imatruck.betterweather.BetterWeatherExtension.java

/**
 * Requests a location update if setting is Automatic, else it will give a dummy location
 *
 * @param lm       Location Manager from {@link net.imatruck.betterweather.BetterWeatherExtension#onUpdateData(int)}
 * @param provider Provider determined in {@link net.imatruck.betterweather.BetterWeatherExtension#onUpdateData(int)}
 *///from  w ww  .  j  a  va 2 s .  co m
private void requestLocationUpdate(final LocationManager lm, final String provider) {
    if (provider != null && sUseCurrentLocation) {
        if (ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            handleMissingPermission();
            return;
        }
        final Location lastLocation = lm.getLastKnownLocation(provider);
        if (lastLocation == null || (SystemClock.elapsedRealtimeNanos()
                - lastLocation.getElapsedRealtimeNanos()) >= STALE_LOCATION_NANOS) {
            LOGW(TAG,
                    "Stale or missing last-known location; requesting single coarse location " + "update. "
                            + ((lastLocation != null)
                                    ? lastLocation.getLatitude() + ", " + lastLocation.getLongitude()
                                    : "Last location is null"));
            try {
                disableOneTimeLocationListener();
                mOneTimeLocationListenerActive = true;
                lm.requestSingleUpdate(provider, mOneTimeLocationListener, null);
                gpsFixHandler.postDelayed(new Runnable() {
                    public void run() {
                        disableOneTimeLocationListener();
                        LOGD(TAG, "We didn't get a GPS fix quick enough, we'll try again later");
                        scheduleRefresh(0);
                    }
                }, 30 * 1000);
                LOGD(TAG, "Requested single location update");
                if (lastLocation != null) {
                    new RefreshWeatherTask(lastLocation).execute();
                }
            } catch (Exception e) {
                LOGW(TAG, "RuntimeException on requestSingleUpdate. " + e.toString());
                scheduleRefresh(2);
            }
        } else {
            new RefreshWeatherTask(lastLocation).execute();
        }
    } else if (!sUseCurrentLocation) {
        LOGD(TAG, "Using set location");
        disableOneTimeLocationListener();
        Location dummyLocation = new Location(provider);
        new RefreshWeatherTask(dummyLocation).execute();
    } else {
        handleMissingPermission();
    }
}

From source file:com.google.android.apps.paco.ExperimentExecutorCustomRendering.java

private void getBestProvider(LocationManager lm) {
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_COARSE);
    criteria.setAccuracy(Criteria.ACCURACY_FINE);

    String bestProvider = lm.getBestProvider(criteria, true);
    if (bestProvider != null) {
        lm.requestLocationUpdates(bestProvider, 0, 0, this);
        location = lm.getLastKnownLocation(bestProvider);
        for (InputLayout input : locationInputs) {
            input.setLocation(location);
        }/*from w  w  w  .j a  va2s  . c  o m*/

    } else {
        new AlertDialog.Builder(this).setMessage(R.string.need_location).setCancelable(true)
                .setPositiveButton(R.string.enable_button, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        launchGpsSettings();
                        dialog.dismiss();
                    }
                }).setNegativeButton(R.string.cancel_button, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                }).create().show();
    }
}

From source file:com.luke.lukef.lukeapp.fragments.MapViewFragment.java

/**
 * Sets up the Google Map Fragment/*from w  w  w  .  j a v a2 s. co m*/
 */
private void setupGoogleMap() {
    LocationManager lm = (LocationManager) getMainActivity().getSystemService(Context.LOCATION_SERVICE);
    //check for permissions and get last known location of the device
    if (ActivityCompat.checkSelfPermission(getMainActivity(),
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(getMainActivity(),
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        getMainActivity().checkPermissions();
        this.lastKnownLoc = lm.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
    } else {
        this.lastKnownLoc = lm.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
    }
}

From source file:at.ac.uniklu.mobile.sportal.service.MutingService.java

private void mute(int alarmId) {
    Log.d(TAG, "mute()");

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);

    if (Preferences.getLocationStatus(preferences) == Preferences.LOCATION_STATUS_WAITING) {
        Log.d(TAG, "mute() blocked - waiting for a location update");
        return;//  w w w. j av a 2s  . c o m
    }

    // check if phone is already muted by the user
    AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
    boolean isPhoneAlreadyMuted = audioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL
            && !Preferences.isMutingPeriod(preferences);
    if (isPhoneAlreadyMuted) {
        Log.d(TAG, "phone is already muted, scheduling next mute");
        scheduleMute(true);
        return;
    }

    // load the current period from the db
    MutingPeriod mutingPeriod = null;
    Log.d(TAG, "muting period id: " + alarmId);
    if (DEBUG_WITH_FAKE_ALARMS) {
        mutingPeriod = new MutingPeriod();
        mutingPeriod.setId(-1);
        mutingPeriod.setBegin(System.currentTimeMillis());
        mutingPeriod.setEnd(mutingPeriod.getBegin() + 10000);
        mutingPeriod.setName("Fakeevent");
    } else {
        mutingPeriod = Studentportal.getStudentPortalDB().mutingPeriods_getPeriod(alarmId);
    }

    // check if phone is located at university
    notifyUser(Studentportal.NOTIFICATION_MS_INFO, true, mutingPeriod.getName(), mutingPeriod.getName(),
            getString(R.string.automute_notification_course_started_locating));
    boolean isPhoneLocationKnown = false;
    boolean isPhoneLocatedAtUniversity = false;
    String locationSource = null;

    WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
    if (wifiManager.isWifiEnabled()) {
        ScanResult scanResult = MutingUtils.findMutingWifiNetwork(wifiManager.getScanResults());
        if (scanResult != null) {
            Log.d(TAG, "phone located by wifi: " + scanResult.SSID);
            isPhoneLocationKnown = true;
            isPhoneLocatedAtUniversity = true;
            locationSource = "wifi (" + scanResult.SSID + ")";
        }
    }

    if (!isPhoneLocationKnown) {
        // phone location could not be determined by wifi, trying network location instead...
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            Intent locationIntent = new Intent("at.ac.uniklu.mobile.sportal.LOCATION_UPDATE")
                    .putExtra(EXTRA_ALARM_ID, alarmId);
            PendingIntent pendingLocationIntent = PendingIntent.getBroadcast(this, 0, locationIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            // remove the location receiver (so it doesn't get registered multiple times [could also happen on overlapping mute() calls)
            locationManager.removeUpdates(pendingLocationIntent);

            if (Preferences.getLocationStatus(preferences) == Preferences.LOCATION_STATUS_RECEIVED) {
                isPhoneLocationKnown = true;
                pendingLocationIntent.cancel();
                Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                if (location == null) {
                    Log.d(TAG, "location received but still null");
                } else {
                    MutingRegion mutingRegion = MutingUtils.findOverlappingMutingRegion(location);
                    if (mutingRegion != null) {
                        Log.d(TAG, "phone located by network @ " + mutingRegion.getName());
                        isPhoneLocatedAtUniversity = true;
                        locationSource = "location (" + mutingRegion.getName() + ")";
                    }
                }
            } else {
                Log.d(TAG, "trying to locate the phone by network...");
                // wait for a location update
                Preferences.setLocationStatus(preferences, Preferences.LOCATION_STATUS_WAITING);
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
                        pendingLocationIntent);
                return; // exit method - it will be re-called from the location broadcast receiver on a location update
            }
        }
    }

    boolean isAlwaysMuteEnabled = Preferences.isAutomuteWithoutLocation(this, preferences);

    if (isPhoneLocationKnown) {
        if (!isPhoneLocatedAtUniversity) {
            Log.d(TAG, "phone is not located at university, scheduling next mute");
            scheduleMute(true);
            removeNotification(Studentportal.NOTIFICATION_MS_INFO);
            return;
        }
    } else {
        Log.d(TAG, "phone cannot be located");
        if (!isAlwaysMuteEnabled) {
            Log.d(TAG, "alwaysmute is disabled, scheduling next mute");
            Preferences.setLocationStatus(preferences, Preferences.LOCATION_STATUS_NONE);
            scheduleMute(true);
            removeNotification(Studentportal.NOTIFICATION_MS_INFO);
            return;
        }
    }

    // only turn the ringtone off if we aren't currently in a muting period.
    // if we are in a muting period the ringtone is already muted and the request should be ignored,
    // else rintoneTurnOn() won't turn the ringtone back on because ringtone override will be set to true
    if (!Preferences.isMutingPeriod(preferences)) {
        MutingUtils.ringtoneTurnOff(this);
    }

    // persist that from now on the phone is in a muting period
    Preferences.setMutingPeriod(preferences, true);

    // inform user via a notification that a course has started and the phone has been muted
    notifyUser(Studentportal.NOTIFICATION_MS_INFO, true, mutingPeriod.getName(), mutingPeriod.getName(),
            getString(R.string.automute_notification_course_muted));

    final boolean isPhoneLocationKnownAnalytics = isPhoneLocationKnown;
    final String locationSourceAnalytics = locationSource;
    Analytics.onEvent(Analytics.EVENT_MUTINGSERVICE_MUTE, "isPhoneLocationKnown",
            isPhoneLocationKnownAnalytics + "", "locationSource", locationSourceAnalytics);

    scheduleUnmute(mutingPeriod.getEnd());
}

From source file:com.lauszus.launchpadflightcontrollerandroid.app.MapFragment.java

@Override
public void onResume() {
    super.onResume();
    LocationManager locationManager = (LocationManager) getActivity()
            .getSystemService(Context.LOCATION_SERVICE);
    if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        new AlertDialog.Builder(getActivity())
                .setMessage("Your GPS seems to be disabled, do you want to enable it?").setCancelable(false)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int id) {
                        startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                    }// ww  w.j a v a  2 s  . c  o  m
                }).setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int id) {
                        dialog.cancel();
                        Toast.makeText(getActivity(), "GPS must be on in order to use this application!",
                                Toast.LENGTH_LONG).show();
                        getActivity().finish();
                    }
                }).create().show();
    } else {
        setUpMapIfNeeded();
        if (ActivityCompat.checkSelfPermission(getActivity(),
                Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            Location location = locationManager
                    .getLastKnownLocation(locationManager.getBestProvider(new Criteria(), false));
            if (location != null) {
                LatLng myLocation = new LatLng(location.getLatitude(), location.getLongitude());
                mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(myLocation, 19.0f));
            }
        }
    }
}

From source file:pandroid.agent.PandroidAgentListener.java

private void gpsLocation() {
    // Starts with GPS, if no GPS then gets network location
    //       /*from w  w  w .ja  va  2 s .  com*/
    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    List<String> providers = lm.getProviders(true);
    Log.d("PANDROID providers count", "" + providers.size());

    /* Loop over the array backwards, and if you get an accurate location, then break out the loop*/
    Location loc = null;

    for (int i = providers.size() - 1; i >= 0; i--) {
        Log.d("PANDROID providers", providers.get(i));
        loc = lm.getLastKnownLocation(providers.get(i));
        if (loc != null)
            break;
    }

    if (loc != null) {
        Log.d("PANDROID", "loc != null");
        //if(latitude != loc.getLatitude() || longitude != loc.getLongitude()) {
        lastGpsContactDateTime = getHumanDateTime(-1);
        //`}
        Log.d("LATITUDE", Double.valueOf(loc.getLatitude()).toString());
        Log.d("LONGITUDE", Double.valueOf(loc.getLongitude()).toString());
        putSharedData("PANDROID_DATA", "latitude", Double.valueOf(loc.getLatitude()).toString(), "float");
        putSharedData("PANDROID_DATA", "longitude", Double.valueOf(loc.getLongitude()).toString(), "float");
    }
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_COARSE);
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);
    criteria.setCostAllowed(true);
    String bestProvider = lm.getBestProvider(criteria, true);

    // If not provider found, abort GPS retrieving
    if (bestProvider == null) {
        Log.e("LOCATION", "No location provider found!");
        return;
    }

    lm.requestLocationUpdates(bestProvider, Core.interval, 15, new LocationListener() {
        public void onLocationChanged(Location location) {
            Log.d("Best latitude", Double.valueOf(location.getLatitude()).toString());
            putSharedData("PANDROID_DATA", "latitude", Double.valueOf(location.getLatitude()).toString(),
                    "float");
            Log.d("Best longitude", Double.valueOf(location.getLongitude()).toString());
            putSharedData("PANDROID_DATA", "longitude", Double.valueOf(location.getLongitude()).toString(),
                    "float");
        }

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

        }

        public void onProviderEnabled(String s) {
            // try switching to a different provider
        }

        public void onProviderDisabled(String s) {
            putSharedData("PANDROID_DATA", "enabled_location_provider", "disabled", "string");
        }
    });
    //}

}

From source file:com.example.angel.parkpanda.MainActivity.java

private Location MMgetMyLocation() {
    LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String provider = service.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) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.

    }/*w  ww  . j a v  a 2s. c  o m*/
    Location location = service.getLastKnownLocation(provider);

    return location;
}

From source file:com.seatgeek.placesautocompletedemo.MainFragment.java

private LatLng getLastKnownLocation(boolean isMoveMarker) {
    LocationManager lm = (LocationManager) TheApp.getAppContext().getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_LOW);
    String provider = lm.getBestProvider(criteria, true);
    if (provider == null) {
        return null;
    }//w  ww .  j a  va  2  s .com
    Activity activity = getActivity();
    if (activity == null) {
        return null;
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (activity.checkSelfPermission(
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && activity.checkSelfPermission(
                        Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return null;
        }
    }
    Location loc = lm.getLastKnownLocation(provider);
    if (loc != null) {
        LatLng latLng = new LatLng(loc.getLatitude(), loc.getLongitude());
        if (isMoveMarker) {
            moveMarker(latLng);
        }
        return latLng;
    }
    return null;
}