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:uk.ac.horizon.ug.exploding.client.LocationUtils.java

public static void registerOnThread(Context context, LocationListener locationCallback, Listener listener) {
    LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    List<String> providers = locationManager.getAllProviders();
    Log.i(TAG, "Found " + providers.size() + " location providers");
    for (String provider : providers) {
        if (locationManager.isProviderEnabled(provider)) {
            Log.i(TAG, "Provider " + provider + " enabled");
        } else {// w ww.  j  ava2  s .c o m
            Log.i(TAG, "Provider " + provider + " disabled");
        }
    }
    for (int pi = 0; pi < PROVIDERS.length; pi++) {
        String provider = PROVIDERS[pi];
        if (locationManager.isProviderEnabled(provider)) {
            Log.i(TAG, "Registering with provider " + provider);
            Location loc = locationManager.getLastKnownLocation(provider);
            if (loc != null) {
                Log.i(TAG,
                        "Last Location, provider=" + loc.getProvider() + ", lat=" + loc.getLatitude()
                                + ", long=" + loc.getLongitude() + ", bearing="
                                + (loc.hasBearing() ? "" + loc.getBearing() : "NA") + ", speed="
                                + (loc.hasSpeed() ? "" + loc.getSpeed() : "NA") + ", accuracy="
                                + (loc.hasAccuracy() ? "" + loc.getAccuracy() : "NA") + ", alt="
                                + (loc.hasAltitude() ? "" + loc.getAltitude() : "NA"));

                ZoneService.updateLocation(context, loc);

            }
            //if (!"passive".equals(provider))
            if (locationCallback != null)
                locationManager.requestLocationUpdates(provider, 0/*minTime*/, 0/*minDistance*/,
                        locationCallback);
        } else
            Log.e(TAG, "Required provider " + provider + " not enabled!");
    }
    if (listener != null)
        locationManager.addGpsStatusListener(listener);
}

From source file:com.entertailion.android.slideshow.images.PanoramioImageLoader.java

public PanoramioImageLoader(ImageManager sInstance, String query) {
    super(sInstance, query);
    Context context = sInstance.getContext();
    try {//from   w ww  . j  ava  2 s .c  o m
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        Location location = locationManager.getLastKnownLocation("static");
        mMinLong = mMaxLong = location.getLongitude();
        mMinLat = mMaxLat = location.getLatitude();
    } catch (Exception e) {
        Log.e(LOG_TAG, "LocationManager error", e);
    }
}

From source file:eu.inmite.apps.smsjizdenka.fragment.CitiesFragment.java

@Override
public Loader<Object> onCreateLoader(int id, Bundle arg1) {
    if (id == Constants.LOADER_CITIES) {
        return new WrappedAsyncTaskLoader<Object>(c) {

            @Override/*from  ww w . ja  va 2  s .c  o m*/
            public Object loadInBackground() {
                List<CitiesAdapter.Item> items = new ArrayList<CitiesAdapter.Item>();
                CityManager cm = CityManager.get(c);
                // one closest
                LocationManager lm = (LocationManager) c.getSystemService(Context.LOCATION_SERVICE);
                Location location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                if (location != null) {
                    City closest = cm.getClosest(c, location.getLatitude(), location.getLongitude());
                    if (closest != null) {
                        items.add(new CitiesAdapter.Item(CitiesAdapter.Item.TYPE_HEADER,
                                c.getString(R.string.cities_nearest)));
                        items.add(new CitiesAdapter.Item(CitiesAdapter.Item.TYPE_CITY, closest.city));
                    }
                }
                // two last
                List<City> lastTwo = cm.getLastTwoUsed(c);
                if (lastTwo.size() > 0) {
                    items.add(new CitiesAdapter.Item(CitiesAdapter.Item.TYPE_HEADER,
                            c.getString(R.string.cities_recently_purchased)));
                    items.add(new CitiesAdapter.Item(CitiesAdapter.Item.TYPE_CITY, lastTwo.get(0).city));
                    if (lastTwo.size() == 2) {
                        items.add(new CitiesAdapter.Item(CitiesAdapter.Item.TYPE_CITY, lastTwo.get(1).city));
                    }
                }
                // all alphabetically
                List<City> all = cm.getUniqueCities(c);
                items.add(new CitiesAdapter.Item(CitiesAdapter.Item.TYPE_HEADER,
                        c.getString(R.string.cities_all_tickets)));
                for (City city : all) {
                    items.add(new CitiesAdapter.Item(CitiesAdapter.Item.TYPE_CITY, city.city));
                }
                return items;
            }
        };
    }
    return null;
}

From source file:org.melato.bus.android.activity.PlanTabsActivity.java

Point2D getCurrentLocation() {
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    return Locations.location2Point(location);
}

From source file:au.id.tedp.mapdroid.Picker.java

public Location getLastLocation(Context ctx) {
    LocationManager locmgr = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
    Location l = locmgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if (l != null)
        return l;
    return locmgr.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}

From source file:org.ohmage.appwidget.StressButtonService.java

private void storeResponse(String surveyId, String surveyTitle, String launchTime, List<Prompt> prompts) {

    SharedPreferencesHelper helper = new SharedPreferencesHelper(this);
    //String campaign = helper.getCampaignName();
    //String campaignVersion = helper.getCampaignUrn();
    String username = helper.getUsername();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Calendar now = Calendar.getInstance();
    String date = dateFormat.format(now.getTime());
    long time = now.getTimeInMillis();
    String timezone = TimeZone.getDefault().getID();

    LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if (loc == null || System.currentTimeMillis() - loc.getTime() > SurveyGeotagService.LOCATION_STALENESS_LIMIT
            || loc.getAccuracy() > SurveyGeotagService.LOCATION_ACCURACY_THRESHOLD) {
        Log.w(TAG, "gps provider disabled or location stale or inaccurate");
        loc = null;/*w  w w.j a  v a 2 s.c  o m*/
    }

    //get launch context from trigger glue
    JSONObject surveyLaunchContextJson = new JSONObject();
    /*try {
       //surveyLaunchContextJson.put("launch_time", launchTime);
       //surveyLaunchContextJson.put("active_triggers", TriggerFramework.getActiveTriggerInfo(this, surveyTitle));
    } catch (JSONException e1) {
       throw new RuntimeException(e1);
    }*/
    String surveyLaunchContext = surveyLaunchContextJson.toString();

    JSONArray responseJson = new JSONArray();
    for (int i = 0; i < prompts.size(); i++) {
        JSONObject itemJson = new JSONObject();
        try {
            itemJson.put("prompt_id", ((AbstractPrompt) prompts.get(i)).getId());
            itemJson.put("value", ((AbstractPrompt) prompts.get(i)).getResponseObject());
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        responseJson.put(itemJson);
    }
    String response = responseJson.toString();

    DbHelper dbHelper = new DbHelper(this);
    if (loc != null) {
        //dbHelper.addResponseRow(campaign, campaignVersion, username, date, time, timezone, SurveyGeotagService.LOCATION_VALID, loc.getLatitude(), loc.getLongitude(), loc.getProvider(), loc.getAccuracy(), loc.getTime(), surveyId, surveyLaunchContext, response);
    } else {
        //dbHelper.addResponseRowWithoutLocation(campaign, campaignVersion, username, date, time, timezone, surveyId, surveyLaunchContext, response);
    }
}

From source file:ca.ualberta.cs.cmput301w15t04team04project.FragmentEditClaim2.java

public void getClaimLocation(View view) {

    LocationManager lm = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
    Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, listener);

}

From source file:ca.ualberta.cs.cmput301w15t04team04project.EditClaimActivity.java

/**
 *//*from www  .  ja v  a2 s .  c om*/

public void getClaimLocation(View view) {

    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, listener);
    claimLocation = location;

}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.action_my_location:
        try {/*  w w w.  j a v  a 2 s  . com*/
            LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
            GeoPoint userLocation = new GeoPoint(
                    locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER));
            mapController.animateTo(userLocation);
            return true;
        } catch (NullPointerException ex) {
            Toast.makeText(this, getString(R.string.location_not_found), Toast.LENGTH_LONG).show();
            Log.e(TAG, "Location not found");
            return true;
        }
    case android.R.id.home:
        NavUtils.navigateUpFromSameTask(this);
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:com.ibm.mil.readyapps.telco.hotspots.HotSpotActivity.java

private Location initUserMarker() {
    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    Location userLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    LatLng userPosition = DEFAULT_LOCATION; // default if no user location exists
    if (userLocation != null) {
        userPosition = new LatLng(userLocation.getLatitude(), userLocation.getLongitude());
    }/*from   w w w.ja  v a2  s .  com*/

    userMarker = map.addMarker(new MarkerOptions().position(userPosition).anchor(0.5f, 0.5f)
            .icon(BitmapDescriptorFactory.fromResource(R.drawable.person)));

    return MapUtils.convertLatLng(userMarker.getPosition());
}