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:com.wikitude.example.ARBrowserActivity.java

/** Called when the activity is first created. */
@Override/*w  w  w .  jav  a2 s  . c  o  m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // let the application be fullscreen
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

    // check if the device fulfills the SDK'S minimum requirements
    if (!ArchitectView.isDeviceSupported(this)) {
        Toast.makeText(this, "minimum requirements not fulfilled", Toast.LENGTH_LONG).show();
        this.finish();
        return;
    }
    setContentView(R.layout.main);

    // set the devices' volume control to music to be able to change the
    // volume of possible soundfiles to play
    this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
    this.architectView = (ArchitectView) this.findViewById(R.id.architectView);
    // onCreate method for setting the license key for the SDK
    architectView.onCreate(apiKey);

    // in order to inform the ARchitect framework about the user's location
    // Androids LocationManager is used in this case
    // NOT USED IN THIS EXAMPLE
    // locManager =
    // (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    // locManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0,
    // 0, this);

    // 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);

    locationManager.requestLocationUpdates(provider, 20000, 0, this);

    // Getting latitude of the current location
    fLat = location.getLatitude();

    // Getting longitude of the current location
    fLng = location.getLongitude();

}

From source file:com.example.frodo.MapActivity.java

/**
 * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
 * installed) and the map has not already been instantiated.. This will ensure that we only ever
 * call {@link #setUpMap()} once when {@link #mMap} is not null.
 * <p>/*from  w  ww .ja  va  2  s . c o m*/
 * If it isn't installed {@link SupportMapFragment} (and
 * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
 * install/update the Google Play services APK on their device.
 * <p>
 * A user can return to this FragmentActivity after following the prompt and correctly
 * installing/updating/enabling the Google Play services. Since the FragmentActivity may not have been
 * completely destroyed during this process (it is likely that it would only be stopped or
 * paused), {@link #onCreate(Bundle)} may not be called again so we should call this method in
 * {@link #onResume()} to guarantee that it will be called.
 */
private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.
    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        fMapfragment = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map));
        mMap = fMapfragment.getMap();
        // Check if we were successful in obtaining the map.
        if (mMap != null) {
            setUpMap();
        }
    }
    mapInformation = (TextView) findViewById(R.id.mapInformation);
    mapInformation.setText(R.string.pagetext_location_finding);
    // Acquire a reference to the system Location Manager
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    // get location using same provider criteria as we use for the maps
    String provider = new CurrentLocationProvider(context).getProvider();
    Location currentLocation = locationManager.getLastKnownLocation(provider);
    mapInformation.setText(R.string.pagetext_loading_quests);

    String lookupId = params.getString("ID");
    getQuests(currentLocation, lookupId);
}

From source file:com.metinkale.prayerapp.vakit.AddCity.java

@SuppressWarnings("MissingPermission")
public void checkLocation() {
    if (PermissionUtils.get(this).pLocation) {
        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        Location loc = null;/*w w w .j a v a  2  s.  c om*/
        List<String> providers = lm.getProviders(true);
        for (String provider : providers) {
            Location last = lm.getLastKnownLocation(provider);
            // one hour==1meter in accuracy
            if ((last != null) && ((loc == null)
                    || ((last.getAccuracy() - (last.getTime() / (1000 * 60 * 60))) < (loc.getAccuracy()
                            - (loc.getTime() / (1000 * 60 * 60)))))) {
                loc = last;
            }
        }

        if (loc != null)
            onLocationChanged(loc);

        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_MEDIUM);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(false);
        criteria.setSpeedRequired(false);
        String provider = lm.getBestProvider(criteria, true);
        if (provider != null) {
            lm.requestSingleUpdate(provider, this, null);
        }

    } else {
        PermissionUtils.get(this).needLocation(this);
    }
}

From source file:com.andrew67.ddrfinder.activity.MapViewer.java

/**
 * Zooms and moves the map to the user's last known current location, typically on app startup.
 *//*from www . j  av  a2 s  .co m*/
private void zoomToCurrentLocation() {
    final LocationManager locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
    Location lastKnown = null;
    try {
        lastKnown = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    } catch (SecurityException e) {
        showMessage(R.string.error_perm_loc);
    }
    if (lastKnown != null) {
        mMap.animateCamera(CameraUpdateFactory
                .newLatLngZoom(new LatLng(lastKnown.getLatitude(), lastKnown.getLongitude()), BASE_ZOOM));
    }
}

From source file:com.magicmod.mmweather.MainActivity.java

private void updateByGeoLocation() {
    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Location location = lm.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
    Log.d(TAG, "Current location is " + location);
    boolean needsUpdate = location == null;
    if (location == null) {
        Toast.makeText(mContext, mContext.getString(R.string.geo_location_fail_info), Toast.LENGTH_LONG).show();
    }/*from   www  .jav  a2  s.  co  m*/
    if (location != null) {
        long delta = System.currentTimeMillis() - location.getTime();
        needsUpdate = delta > Constants.OUTDATED_LOCATION_THRESHOLD_MILLIS;
    }
    if (needsUpdate) {
        // TODO: use a better way to get location

    }

    if (location != null) {
        new WeatherUpdateTask(location, Preferences.isMetric(mContext)).execute();
    }
}

From source file:org.ohmage.reminders.base.TriggerBase.java

public void notifyTrigger(Context context, int trigId) {
    Log.v(TAG, "TriggerBase: notifyTrigger(" + trigId + ")");

    // Clear the ignored state for all of this trigger's surveys
    Set<String> surveys = NotifSurveyAdaptor.getSurveysForTrigger(context, trigId);
    for (String survey : surveys) {
        NotifSurveyAdaptor.clearSurveyIgnored(context, survey);
    }//from  ww  w . j  a v a 2  s  . c o  m

    TriggerDB db = new TriggerDB(context);
    db.open();

    String rtDesc = db.getRunTimeDescription(trigId);
    TriggerRunTimeDesc desc = new TriggerRunTimeDesc();

    desc.loadString(rtDesc);

    //Save trigger time stamp in the run time description
    long now = System.currentTimeMillis();
    desc.setTriggerTimeStamp(now);
    //Save trigger current loc in the run time description
    LocationManager locMan = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    Location loc = locMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    desc.setTriggerLocation(loc);

    //Save the run time desc in the database
    db.updateRunTimeDescription(trigId, desc.toString());

    //Call the notifier to display the notification
    //Pass the notification description corresponding to this trigger
    Notifier.notifyNewTrigger(context, trigId, db.getNotifDescription(trigId));

    db.close();

    // Set all the surveys which were triggered to the pending state
    setTriggerSurveysPending(context, now, trigId);
}

From source file:org.redbus.ui.stopmap.StopMapActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.stop_map);/*w w w . j a  v a  2 s.  co m*/
    busyDialog = new BusyDialog(this);

    this.pointTree = StopDbHelper.Load(this);

    // Load in all the required BitmapDescriptors:
    unknownStopBitmap = BitmapDescriptorFactory.fromResource(R.drawable.stop_unknown);
    compassBitmaps = new HashMap<Integer, BitmapDescriptor>();
    compassBitmaps.put(StopDbHelper.STOP_FACING_N, BitmapDescriptorFactory.fromResource(R.drawable.compass_n));
    compassBitmaps.put(StopDbHelper.STOP_FACING_NE,
            BitmapDescriptorFactory.fromResource(R.drawable.compass_ne));
    compassBitmaps.put(StopDbHelper.STOP_FACING_E, BitmapDescriptorFactory.fromResource(R.drawable.compass_e));
    compassBitmaps.put(StopDbHelper.STOP_FACING_SE,
            BitmapDescriptorFactory.fromResource(R.drawable.compass_se));
    compassBitmaps.put(StopDbHelper.STOP_FACING_S, BitmapDescriptorFactory.fromResource(R.drawable.compass_s));
    compassBitmaps.put(StopDbHelper.STOP_FACING_SW,
            BitmapDescriptorFactory.fromResource(R.drawable.compass_sw));
    compassBitmaps.put(StopDbHelper.STOP_FACING_W, BitmapDescriptorFactory.fromResource(R.drawable.compass_w));
    compassBitmaps.put(StopDbHelper.STOP_FACING_NW,
            BitmapDescriptorFactory.fromResource(R.drawable.compass_nw));
    compassBitmaps.put(StopDbHelper.STOP_OUTOFORDER,
            BitmapDescriptorFactory.fromResource(R.drawable.stop_outoforder));
    compassBitmaps.put(StopDbHelper.STOP_DIVERTED,
            BitmapDescriptorFactory.fromResource(R.drawable.stop_diverted));
    compassBitmaps = Collections.unmodifiableMap(compassBitmaps);

    // Get a reference to the map:
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    map = mapFragment.getMap();
    if (map != null) {
        map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                LatLng point = marker.getPosition();
                final int nearestStopNodeIdx = pointTree.findNearest((int) (point.latitude * 1E6),
                        (int) (point.longitude * 1E6));
                final int stopCode = pointTree.stopCode[nearestStopNodeIdx];
                new StopMapPopup(StopMapActivity.this, stopCode);
                return true;
            }
        });
        map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        map.setIndoorEnabled(false);
        map.setMyLocationEnabled(true);
        UiSettings mapSettings = map.getUiSettings();
        mapSettings.setCompassEnabled(false);
        mapSettings.setRotateGesturesEnabled(false);
        mapSettings.setTiltGesturesEnabled(false);

        // mapController.setZoom(17);

        // Check to see if we've been passed data
        int lat = getIntent().getIntExtra("Lat", -1);
        int lng = getIntent().getIntExtra("Lng", -1);

        if (lat == -1 || lng == -1) {
            Log.d(TAG, "Not supplied with either lat or lng");
            // if we don't have a location supplied, try and use the last known one.
            LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
            Location gpsLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            Location networkLocation = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

            if ((gpsLocation != null) && (gpsLocation.getAccuracy() < 100)) {
                Log.d(TAG, "Using GPS for location. " + gpsLocation);

                zoomTo(new LatLng(gpsLocation.getLatitude(), gpsLocation.getLongitude()));
            } else if ((networkLocation != null) && (networkLocation.getAccuracy() < 100)) {
                Log.d(TAG, "Using network for location.");
                zoomTo(new LatLng(networkLocation.getLatitude(), networkLocation.getLongitude()));

            } else {
                Log.d(TAG, "Using default location from db.");
                StopDbHelper stopDb = StopDbHelper.Load(this);
                zoomTo(new LatLng(stopDb.defaultMapLocationLat / 1E6, stopDb.defaultMapLocationLon / 1E6));
            }
            updateMyLocationStatus(true);
        } else {
            Log.d(TAG, "Using supplied lat and lng.");
            zoomTo(new LatLng(lat / 1E6, lng / 1E6));
            updateMyLocationStatus(false);
        }
        map.setOnCameraChangeListener(this);
    }
}

From source file:com.temboo.example.FoursquareConnectedActivity.java

/**
 * onCreate is called by Android when the activity is first created.
 */// w ww. ja va2 s.c  om
@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    // Initialize the UI with the "connected mode" layout (defined in /res/layout/foursquare_connected.xml)
    setContentView(R.layout.foursquare_connected);

    // Obtain a reference to the "current venue" textview
    currentVenueTextView = (TextView) findViewById(R.id.foursquareVenueField);

    // Initiate the Temboo session
    try {
        session = new MyTemboo(TEMBOO_APPKEY_NAME, TEMBOO_APPKEY);
    } catch (Exception e) {
        currentVenueTextView.setText("Uh-oh! Something has gone horribly wrong.");
        Log.e("TEMBOO", "Error starting Temboo session.", e);
    }

    // Debug: display the Fourquare Oauth token retrieved by FoursquareOauthActivity
    Toast.makeText(FoursquareConnectedActivity.this,
            "Successfully connected to Foursquare. Oauth token: " + FOURSQUARE_OAUTH_TOKEN, Toast.LENGTH_SHORT)
            .show();

    // Obtain a reference to the Android LocationManager, which is (surprisingly) responsible for managing GPS/location data
    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

    // Get and store the last known location
    currentLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    // Register a listener with the Location Manager to receive location updates. Currently, this is configured
    // to request GPS updates every 3 minutes, with a minimum location-differential of 3 meters per update. 
    // See http://developer.android.com/reference/android/location/LocationManager.html
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 180000, 3, new LocationListener() {

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

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onProviderDisabled(String provider) {
        }

        // When the location changes, store the current location in the parent activity
        @Override
        public void onLocationChanged(Location location) {
            currentLocation = location;
        }
    });

    // Attach the "lookup location" button click handler
    Button lookupButton = (Button) findViewById(R.id.getVenue);
    lookupButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            try {
                getFoursquareVenueForCurrentLocation();
            } catch (Exception e) {
                Log.e("TEMBOO", "Error performing Foursquare venue lookup", e);
                Toast.makeText(FoursquareConnectedActivity.this,
                        "Error performing foursquare venue lookup! " + e.getMessage(), Toast.LENGTH_SHORT)
                        .show();
            }
        }
    });

    // Attach the "Foursquare checkin" button click handler
    Button checkinButton = (Button) findViewById(R.id.doFoursquareCheckin);
    checkinButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            try {
                doFoursquareCheckin();
            } catch (Exception e) {
                Log.e("TEMBOO", "Error performing Foursquare checkin", e);
                Toast.makeText(FoursquareConnectedActivity.this,
                        "Error performing foursquare checkin! " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    });
}

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 va 2 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:com.ibm.mf.geofence.demo.MapsActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    log.debug("***************************************************************************************");
    super.onCreate(savedInstanceState);
    setContentView(R.layout.maps_activity);
    mapCrossHair = (ImageView) findViewById(R.id.map_cross_hair);
    log.debug("in onCreate() tracking is " + (trackingEnabled ? "enabled" : "disabled"));
    addFenceButton = (Button) findViewById(R.id.addFenceButton);
    addFenceButton.setOnClickListener(new View.OnClickListener() {
        @Override//www . j av  a2 s  .  c o  m
        public void onClick(View v) {
            switchMode();
        }
    });
    if (savedInstanceState != null) {
        double[] loc = savedInstanceState.getDoubleArray("currentLocation");
        if (loc != null) {
            currentLocation = new Location(LocationManager.NETWORK_PROVIDER);
            currentLocation.setLatitude(loc[0]);
            currentLocation.setLongitude(loc[1]);
            currentLocation.setTime(System.currentTimeMillis());
        }
        currentZoom = savedInstanceState.getFloat("zoom", -1f);
        log.debug(String.format("restored currentLocation=%s; currentZoom=%f", currentLocation, currentZoom));
    }
    if (currentLocation == null) {
        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        currentLocation = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    }
    log.debug("onCreate() : init of geofencing service");
    /*
    if (!dbDeleted) {
    dbDeleted = true;
    DemoUtils.deleteGeofenceDB(this);
    }
    */
    initManager();
    /*
    // testing the loading from a zip resource
    manager.loadGeofencesFromResource("com/ibm/pisdk/geofencing/geofence_2016-03-18_14_38_04.zip");
    */
    customHttpService = new CustomHttpService(manager, this, SERVER_URL, USER, PWD);
    try {
        startSimulation(geofenceHolder.getFences());
    } catch (Exception e) {
        log.error("error in startSimulation()", e);
    }
}