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:org.traccar.client.ShortcutActivity.java

@SuppressWarnings("MissingPermission")
private void sendAlarm() {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    String provider = PositionProvider.getProvider(preferences.getString(MainFragment.KEY_ACCURACY, "medium"));

    try {/*w  ww.  j a  va2s.co  m*/
        Location location = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
        if (location != null) {
            sendAlarmLocation(location);
        } else {
            locationManager.requestSingleUpdate(provider, new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    sendAlarmLocation(location);
                }

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

                @Override
                public void onProviderEnabled(String provider) {
                }

                @Override
                public void onProviderDisabled(String provider) {
                }
            }, Looper.myLooper());
        }
    } catch (RuntimeException e) {
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
    }
}

From source file:nodomain.freeyourgadget.gadgetbridge.externalevents.AlarmReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    if (!GBApplication.getPrefs().getBoolean("send_sunrise_sunset", false)) {
        LOG.info("won't send sunrise and sunset events (disabled in preferences)");
        return;/* w  ww . j  a v  a2  s  .com*/
    }
    LOG.info("will resend sunrise and sunset events");

    final GregorianCalendar dateTimeTomorrow = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
    dateTimeTomorrow.set(Calendar.HOUR, 0);
    dateTimeTomorrow.set(Calendar.MINUTE, 0);
    dateTimeTomorrow.set(Calendar.SECOND, 0);
    dateTimeTomorrow.set(Calendar.MILLISECOND, 0);
    dateTimeTomorrow.add(GregorianCalendar.DAY_OF_MONTH, 1);

    /*
     * rotate ids ud reuse the id from two days ago for tomorrow, this way we will have
     * sunrise /sunset for 3 days while sending only sunrise/sunset per day
     */
    byte id_tomorrow = (byte) ((dateTimeTomorrow.getTimeInMillis() / (1000L * 60L * 60L * 24L)) % 3);

    GBApplication.deviceService().onDeleteCalendarEvent(CalendarEventSpec.TYPE_SUNRISE, id_tomorrow);
    GBApplication.deviceService().onDeleteCalendarEvent(CalendarEventSpec.TYPE_SUNSET, id_tomorrow);

    Prefs prefs = GBApplication.getPrefs();

    float latitude = prefs.getFloat("location_latitude", 0);
    float longitude = prefs.getFloat("location_longitude", 0);
    LOG.info("got longitude/latitude from preferences: " + latitude + "/" + longitude);

    if (ActivityCompat.checkSelfPermission(context,
            Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
            && prefs.getBoolean("use_updated_location_if_available", false)) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String provider = locationManager.getBestProvider(criteria, false);
        if (provider != null) {
            Location lastKnownLocation = locationManager.getLastKnownLocation(provider);
            if (lastKnownLocation != null) {
                latitude = (float) lastKnownLocation.getLatitude();
                longitude = (float) lastKnownLocation.getLongitude();
                LOG.info("got longitude/latitude from last known location: " + latitude + "/" + longitude);
            }
        }
    }
    GregorianCalendar[] sunriseTransitSetTomorrow = SPA.calculateSunriseTransitSet(dateTimeTomorrow, latitude,
            longitude, DeltaT.estimate(dateTimeTomorrow));

    CalendarEventSpec calendarEventSpec = new CalendarEventSpec();
    calendarEventSpec.durationInSeconds = 0;
    calendarEventSpec.description = null;

    calendarEventSpec.type = CalendarEventSpec.TYPE_SUNRISE;
    calendarEventSpec.title = "Sunrise";
    if (sunriseTransitSetTomorrow[0] != null) {
        calendarEventSpec.id = id_tomorrow;
        calendarEventSpec.timestamp = (int) (sunriseTransitSetTomorrow[0].getTimeInMillis() / 1000);
        GBApplication.deviceService().onAddCalendarEvent(calendarEventSpec);
    }

    calendarEventSpec.type = CalendarEventSpec.TYPE_SUNSET;
    calendarEventSpec.title = "Sunset";
    if (sunriseTransitSetTomorrow[2] != null) {
        calendarEventSpec.id = id_tomorrow;
        calendarEventSpec.timestamp = (int) (sunriseTransitSetTomorrow[2].getTimeInMillis() / 1000);
        GBApplication.deviceService().onAddCalendarEvent(calendarEventSpec);
    }
}

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

private void submitReport() {
    if (bitmapPicture == null) {
        DialogUtils.show(ReportActivity.this, "To submit a report, you need to take an representative image.");
        return;//from  w  ww  .j a  v a2  s  .c om
    }

    if (this.currentLocation == null) {
        LocationManager locationManager = (LocationManager) ReportActivity.this
                .getSystemService(LOCATION_SERVICE);
        this.currentLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (this.currentLocation == null) {
            DialogUtils.show(ReportActivity.this, "Unable to get your current location.");
            return;
        }
    }

    Report newReport = new Report();
    newReport.setLatitude((float) this.currentLocation.getLatitude());
    newReport.setLongitude((float) this.currentLocation.getLongitude());
    newReport.setSubmitDate(new DateTime(new Date()));
    newReport.setUser(AuthUtils.getAccount());
    newReport.setListTag(new ArrayList(tagList.values()));

    ReportCallbackImpl callback = new ReportCallbackWithResult(ReportActivity.this);
    new AddReportAsyncTask(this, callback, AuthUtils.getCredential(), newReport, bitmapPicture).execute();
}

From source file:com.dwdesign.tweetings.activity.NearbyMapViewerActivity.java

protected void getLocationAndCenterMap() {
    LocationManager mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    final Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    final String provider = mLocationManager.getBestProvider(criteria, true);

    Location mRecentLocation = null;

    if (provider != null) {
        mRecentLocation = mLocationManager.getLastKnownLocation(provider);
    } else {/*from w ww.  j av  a 2 s . c  o  m*/
        Toast.makeText(this, R.string.cannot_get_location, Toast.LENGTH_SHORT).show();
    }

    if (mRecentLocation != null && isNativeMapSupported()) {
        NativeNearbyMapFragment aFragment = (NativeNearbyMapFragment) mFragment;
        aFragment.setCenter(mRecentLocation);
    }
}

From source file:be.brunoparmentier.openbikesharing.app.activities.MapActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map);
    getActionBar().setDisplayHomeAsUpEnabled(true);

    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);

    stationsDataSource = new StationsDataSource(this);
    ArrayList<Station> stations = stationsDataSource.getStations();

    map = (MapView) findViewById(R.id.mapView);
    stationMarkerInfoWindow = new StationMarkerInfoWindow(R.layout.bonuspack_bubble, map);

    /* handling map events */
    MapEventsOverlay mapEventsOverlay = new MapEventsOverlay(this, this);
    map.getOverlays().add(0, mapEventsOverlay);

    /* markers list */
    GridMarkerClusterer stationsMarkers = new GridMarkerClusterer(this);
    Drawable clusterIconD = getResources().getDrawable(R.drawable.marker_cluster);
    Bitmap clusterIcon = ((BitmapDrawable) clusterIconD).getBitmap();
    map.getOverlays().add(stationsMarkers);
    stationsMarkers.setIcon(clusterIcon);
    stationsMarkers.setGridSize(100);/*from ww w .j  a  v a 2 s  . co  m*/

    for (final Station station : stations) {
        stationsMarkers.add(createStationMarker(station));
    }
    map.invalidate();

    mapController = map.getController();
    mapController.setZoom(16);

    map.setMultiTouchControls(true);
    map.setBuiltInZoomControls(true);
    map.setMinZoomLevel(3);

    /* map tile source */
    String mapLayer = settings.getString("pref_map_layer", "");
    switch (mapLayer) {
    case "mapnik":
        map.setTileSource(TileSourceFactory.MAPNIK);
        break;
    case "cyclemap":
        map.setTileSource(TileSourceFactory.CYCLEMAP);
        break;
    case "osmpublictransport":
        map.setTileSource(TileSourceFactory.PUBLIC_TRANSPORT);
        break;
    case "mapquestosm":
        map.setTileSource(TileSourceFactory.MAPQUESTOSM);
        break;
    default:
        map.setTileSource(TileSourceFactory.DEFAULT_TILE_SOURCE);
        break;
    }

    GpsMyLocationProvider imlp = new GpsMyLocationProvider(this.getBaseContext());
    imlp.setLocationUpdateMinDistance(1000);
    imlp.setLocationUpdateMinTime(60000);

    myLocationOverlay = new MyLocationNewOverlay(this.getBaseContext(), imlp, this.map);
    map.getOverlays().add(this.myLocationOverlay);

    myLocationOverlay.enableMyLocation();

    try {
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        GeoPoint userLocation = new GeoPoint(
                locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER));
        mapController.animateTo(userLocation);
    } catch (NullPointerException e) {
        mapController.setZoom(13);
        double bikeNetworkLatitude = Double.longBitsToDouble(settings.getLong(PREF_KEY_NETWORK_LATITUDE, 0));
        double bikeNetworkLongitude = Double.longBitsToDouble(settings.getLong(PREF_KEY_NETWORK_LONGITUDE, 0));
        mapController.animateTo(new GeoPoint(bikeNetworkLatitude, bikeNetworkLongitude));

        Toast.makeText(this, R.string.location_not_found, Toast.LENGTH_LONG).show();
    }
}

From source file:com.nextgis.mobile.forms.CameraFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    setRetainInstance(true);//from   w ww . ja  v  a  2s .c  o  m

    View view = inflater.inflate(R.layout.camfragment, container, false);

    Button button = (Button) view.findViewById(R.id.insert_take_photo);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            onCapturePhoto();
        }
    });

    ListView photoList = (ListView) view.findViewById(R.id.poi_photos_list);

    adapter = new SimpleAdapter(view.getContext(), listItems, R.layout.row, new String[] { IMG_NAME, IMG_ROT, },
            new int[] { R.id.image_name, R.id.image_rotation });

    photoList.setAdapter(adapter);

    final LocationManager locationManager = (LocationManager) getActivity()
            .getSystemService(Context.LOCATION_SERVICE);

    if (currentLocation == null) {
        currentLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (currentLocation == null) {
            currentLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        }
    }
    long now = System.currentTimeMillis();
    declination = CompassFragment.getDeclination(currentLocation, now);

    sensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);

    return view;
}

From source file:org.microg.gms.ui.PlacePickerActivity.java

@SuppressWarnings("MissingPermission")
private void updateMapFromLocationManager() {
    LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
    Location last = null;/*from   ww  w.  jav a  2  s. c o  m*/
    for (String provider : lm.getAllProviders()) {
        if (lm.isProviderEnabled(provider)) {
            Location t = lm.getLastKnownLocation(provider);
            if (t != null && (last == null || t.getTime() > last.getTime())) {
                last = t;
            }
        }
    }
    Log.d(TAG, "Set location to " + last);
    if (last != null) {
        mapView.map().setMapPosition(new MapPosition(last.getLatitude(), last.getLongitude(), 4096));
    }
}

From source file:com.dwdesign.tweetings.activity.MapViewerActivity.java

protected void getLocationAndCenterMap() {
    LocationManager mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    final Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    final String provider = mLocationManager.getBestProvider(criteria, true);

    Location mRecentLocation = null;

    if (provider != null) {
        mRecentLocation = mLocationManager.getLastKnownLocation(provider);
    } else {/*  ww w. ja  v a  2 s  .c  om*/
        Toast.makeText(this, R.string.cannot_get_location, Toast.LENGTH_SHORT).show();
    }

    if (mRecentLocation != null && isNativeMapSupported()) {
        NativeMapFragment aFragment = (NativeMapFragment) mFragment;
        aFragment.setCenter(mRecentLocation);
    }
}

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

/** Called when the activity is first created. */
@Override//  ww w .  ja v a  2s.  co m
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initMap();

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

    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();

    Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
    if (location != null) {
        googlemap.animateCamera(CameraUpdateFactory
                .newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 13));

        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(new LatLng(location.getLatitude(), location.getLongitude())) // Sets the center of the map to location user
                .zoom(17) // Sets the zoom
                .bearing(90) // Sets the orientation of the camera to east
                .tilt(40) // Sets the tilt of the camera to 30 degrees
                .build(); // Creates a CameraPosition from the builder
        googlemap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

    }

    if (provider == null) {
        onProviderDisabled(provider);
    }
    data = new MarkerDataSource(context);
    try {
        data.open();

    } catch (Exception e) {
        Log.i("hello", "hello");
    }

    List<MyMarkerObj> m = data.getMyMarkers();
    for (int i = 0; i < m.size(); i++) {
        String[] slatlng = m.get(i).getPosition().split(" ");
        LatLng lat = new LatLng(Double.valueOf(slatlng[0]), Double.valueOf(slatlng[1]));
        googlemap.addMarker(
                new MarkerOptions().title(m.get(i).getTitle()).snippet(m.get(i).getSnippet()).position(lat));

        googlemap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {

            public void onInfoWindowClick(Marker marker) {
                Toast.makeText(getBaseContext(), "Info Window clicked@" + marker.getId(), Toast.LENGTH_SHORT)
                        .show();
            }
        });

        //  marker.view();
        //    data.getMarker(new MyMarkerObj(marker.getTitle(), marker.getSnippet(), marker.getPosition().latitude + " " + marker.getPosition().longitude));
    }

    googlemap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {

        public void onMapLongClick(final LatLng latlng) {
            LayoutInflater li = LayoutInflater.from(context);
            final View v = li.inflate(R.layout.alertlayout, null);
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setView(v);
            builder.setCancelable(false);

            builder.setPositiveButton("Create", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    EditText title = (EditText) v.findViewById(R.id.ettitle);
                    EditText snippet = (EditText) v.findViewById(R.id.etsnippet);
                    googlemap.addMarker(new MarkerOptions().title(title.getText().toString())
                            .snippet(snippet.getText().toString())
                            .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))
                            .position(latlng));
                    String sll = latlng.latitude + " " + latlng.longitude;
                    data.addMarker(
                            new MyMarkerObj(title.getText().toString(), snippet.getText().toString(), sll));
                }
            });

            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });

            AlertDialog alert = builder.create();
            alert.show();

        }
    });
}

From source file:uk.ac.horizon.artcodes.fragment.ExperienceRecommendFragment.java

@Nullable
private Location getLocation() {
    if (ContextCompat.checkSelfPermission(getContext(),
            Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        final LocationManager locationManager = (LocationManager) getContext().getApplicationContext()
                .getSystemService(Context.LOCATION_SERVICE);
        float accuracy = Float.MAX_VALUE;
        Location location = null;
        for (String provider : locationManager.getProviders(new Criteria(), true)) {
            Location newLocation = locationManager.getLastKnownLocation(provider);
            if (newLocation != null) {
                if (newLocation.getAccuracy() < accuracy) {
                    accuracy = newLocation.getAccuracy();
                    location = newLocation;
                }/*from   ww w.j  av  a 2 s  .  c om*/
            }
        }

        return location;
    } else {
        Log.i("location", "No location permission");
    }
    return null;
}