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:net.openwatch.acluaz.fragment.FormFragment.java

public JSONObject toJson(ViewGroup container, JSONObject json) {
    String TAG = "FormFragment-ToJSON";
    if (container == null) {
        Log.e(TAG, "null container passed to toJson");
        return new JSONObject();
    }/*from  w ww .  j ava 2s .  c om*/

    if (json == null)
        json = new JSONObject();
    View view;
    for (int x = 0; x < container.getChildCount(); x++) {
        view = container.getChildAt(x);

        if (EditText.class.isInstance(view)) {
            if (view.getTag() != null) {
                if (((EditText) view).getText().toString().compareTo("") == 0)
                    continue; // skip blank input
                try {
                    Log.i(TAG, "Mapping: " + view.getTag().toString() + " value: "
                            + ((EditText) view).getText().toString());
                    if (view.getTag().toString().compareTo(getString(R.string.zipcode_tag)) == 0)
                        json.put(view.getTag().toString(),
                                Integer.parseInt(((EditText) view).getText().toString()));
                    else
                        json.put(view.getTag().toString(), ((EditText) view).getText().toString());
                } catch (JSONException e) {
                    Log.e(TAG, "Error jsonifying text input");
                    e.printStackTrace();
                }

            }
        } else if (CompoundButton.class.isAssignableFrom(view.getClass())) {
            if (view.getTag() != null) {
                // if location toggle, bundle location
                if (((String) view.getTag()).compareTo(getString(R.string.device_location_tag)) == 0
                        && view.getTag(R.id.view_tag) != null) {
                    if (((CompoundButton) view).isChecked()) {
                        try {
                            json.put(getString(R.string.device_lat),
                                    ((Location) view.getTag(R.id.view_tag)).getLatitude());
                            json.put(getString(R.string.device_lon),
                                    ((Location) view.getTag(R.id.view_tag)).getLongitude());
                        } catch (JSONException e) {
                            Log.e(TAG, "Error jsonifying toggle input");
                            e.printStackTrace();
                        }
                    }
                } else if (((String) view.getTag()).compareTo(getString(R.string.device_location_tag)) == 0
                        && view.getTag(R.id.view_tag) == null) {
                    // no location tagged, get last known
                    LocationManager lm = (LocationManager) container.getContext()
                            .getSystemService(Context.LOCATION_SERVICE);
                    Location last = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    try {
                        json.put(getString(R.string.device_lat), last.getLatitude());
                        json.put(getString(R.string.device_lon), last.getLongitude());
                    } catch (JSONException e) {
                        Log.e(TAG, "Error jsonifying last location");
                        e.printStackTrace();
                    } catch (NullPointerException e2) {
                        Log.e(TAG, "No current or historical location info on this device");
                    }
                }

            }
        }

        // combine date and time fields into a single datetime
        if (json.has(getString(R.string.date_tag)) && json.has(getString(R.string.time_tag))) {
            Log.i(TAG, "found date and time tag, let's smush 'em");
            try {
                //TESTING
                //String datetime = combineDateAndTime(json.getString(getString(R.string.date_tag)), json.getString(getString(R.string.time_tag)));
                //Log.i(TAG,"datetime: " + datetime);
                json.put(getString(R.string.date_tag),
                        combineDateAndTime(json.getString(getString(R.string.date_tag)),
                                json.getString(getString(R.string.time_tag))));
                Log.i(TAG, json.toString());
                //json.remove(getString(R.string.date_tag));
                json.remove(getString(R.string.time_tag));
            } catch (JSONException e) {
                Log.e(TAG, "Error creating json datetime field from date and time");
                e.printStackTrace();
            }
        }

    }
    Log.i(TAG, "toJson: " + json.toString());
    return json;

}

From source file:com.metinkale.prayerapp.compass.Main.java

@Override
protected void onResume() {
    super.onResume();
    mSensorManager.unregisterListener(mMagAccel);

    mSensorManager.registerListener(mMagAccel, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
            SensorManager.SENSOR_DELAY_GAME);
    mSensorManager.registerListener(mMagAccel, mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
            SensorManager.SENSOR_DELAY_GAME);

    if (mSelCity == null) {
        mSelCity = (TextView) findViewById(R.id.selcity);
        mSelCity.setOnClickListener(new OnClickListener() {
            @Override/*from   w w w.  java2  s  . com*/
            public void onClick(View arg0) {
                if (App.isOnline()) {
                    startActivity(new Intent(Main.this, LocationPicker.class));
                } else {
                    Toast.makeText(Main.this, R.string.noConnection, Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    if (PermissionUtils.get(this).pLocation) {
        LocationManager locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        List<String> providers = locMan.getProviders(true);
        for (String provider : providers) {
            locMan.requestLocationUpdates(provider, 0, 0, this);
            Location lastKnownLocation = locMan.getLastKnownLocation(provider);
            if (lastKnownLocation != null) {
                calcQiblaAngel(lastKnownLocation);
            }
        }
    }

    if (Prefs.getCompassLat() != 0) {
        Location loc = new Location("custom");
        loc.setLatitude(Prefs.getCompassLat());
        loc.setLongitude(Prefs.getCompassLng());
        calcQiblaAngel(loc);
    }
}

From source file:com.dat255.ht13.grupp23.view.MapView.java

/**
 * Initiating the GoogleMap and all necessary items for the configuration
 * /*from   www  .ja v a  2 s .c o  m*/
 * @param fragmentActivity
 */
private void initiateMap(FragmentActivity fragmentActivity) {
    // Getting Google Play availability status
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(fragmentActivity.getBaseContext());

    // Showing status
    if (status != ConnectionResult.SUCCESS) { // Google Play Services are
        // not available

        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, fragmentActivity, requestCode);
        dialog.show();

    } else { // Google Play Services are available

        // Getting reference to the SupportMapFragment of activity_main.xml
        SupportMapFragment fm = (SupportMapFragment) fragmentActivity.getSupportFragmentManager()
                .findFragmentById(R.id.map);

        // Getting GoogleMap object from the fragment
        googleMap = fm.getMap();

        // Enabling MyLocation Layer of Google Map
        googleMap.setMyLocationEnabled(true);

        // Getting LocationManager object from System Service
        // LOCATION_SERVICE
        LocationManager locationManager = (LocationManager) fragmentActivity
                .getSystemService(Context.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);

        if (location != null) {
            onLocationChanged(location);
            locationManager.requestLocationUpdates(provider, 20000, 0, this);
        }
    }

}

From source file:com.gsma.rcs.ri.messaging.geoloc.EditGeoloc.java

/**
 * Set the location of the device//w ww. ja  va2s .  c  om
 */
protected void setMyLocation() {
    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String bestProvider = lm.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;
    }
    Location lastKnownLoc = lm.getLastKnownLocation(bestProvider);
    if (lastKnownLoc != null) {
        mLatitudeEdit.setText(String.valueOf(lastKnownLoc.getLatitude()));
        mLongitudeEdit.setText(String.valueOf(lastKnownLoc.getLongitude()));
        mAccuracyEdit.setText(String.valueOf(lastKnownLoc.getAccuracy()));
    }
    super.onResume();
}

From source file:org.jraf.android.piclabel.app.form.FormActivity.java

private boolean getLatestLocalLocation(float[] latLon) {
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    List<String> providers = locationManager.getProviders(true);
    Location location = null;//from   ww  w.  ja  v  a 2s . co m
    for (int i = providers.size() - 1; i >= 0; i--) {
        location = locationManager.getLastKnownLocation(providers.get(i));
        if (location != null)
            break;
    }

    if (location == null)
        return false;
    latLon[0] = (float) location.getLatitude();
    latLon[1] = (float) location.getLongitude();
    return true;
}

From source file:com.refujiate.ui.MainMapaActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.tab_ubicacion);
    // 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();/*from ww  w.j  a  va 2 s  . c om*/

    } else { // Google Play Services are available

        // Getting reference to the SupportMapFragment of activity_main.xml
        SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

        // Getting GoogleMap object from the fragment
        googleMap = fm.getMap();

        // Enabling MyLocation Layer of Google Map
        googleMap.setMyLocationEnabled(true);

        googleMap.moveCamera(
                CameraUpdateFactory.newLatLngZoom(new LatLng(-8.105972881341886, -79.028778076171880), 12));

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

        if (location != null) {
            onLocationChanged(location);
        }
        locationManager.requestLocationUpdates(provider, 20000, 0, this);
    }
    addMaker(0);
    Intent svc = new Intent(this, RefugiateService.class);
    startService(svc);
}

From source file:com.example.zenkig.halomap.HaloMapsActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_halo_maps);
    setUpMapIfNeeded();/*from   ww  w .  j a  v  a2 s .  c  o m*/

    tvLocInfo = (TextView) findViewById(R.id.locinfo);

    // mLocationClient = new LocationClient(this, this, this); // create location client

    mMap.setMyLocationEnabled(true); // location layer does not provide data
    mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

    mMap.setOnMapClickListener(this);

    // before loop:
    List<Marker> markers = new ArrayList<Marker>();
    mMap.setOnMapLongClickListener(this);
    // after loop
    markers.size(); // marker numbers size get

    mMap.setOnMarkerDragListener(this);
    mMap.setOnMyLocationChangeListener(this); // listener for location change added
    mMap.setInfoWindowAdapter(new MyInfoWindowAdapter()); // Info window listener adaptor added
    mMap.setOnInfoWindowClickListener(this);

    markerClicked = false;

    // Getting Google Play 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();

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

}

From source file:org.cesar.geofencesdemo.ui.activities.MainActivity.java

private void setUpMapIfNeeded() {

    // Do a null check to confirm that we have not already instantiated the
    // map./*from w w  w.j av a 2  s  .  c  o m*/
    if (mGoogleMap == null) {
        mGoogleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
        // Check if we were successful in obtaining the map.
        if (mGoogleMap != null) {
            // The Map is verified. It is now safe to manipulate the map.
            mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
            mGoogleMap.setMyLocationEnabled(true);
            mGoogleMap.setOnCameraChangeListener(this);

            LatLng latLng = null;
            // If we have a previous location set, we go there
            if (mSimplegeofence != null) {
                latLng = new LatLng(mSimplegeofence.getLatitude(), mSimplegeofence.getLongitude());
            } else {
                // If we don't have a previous location set, we try to go to
                // the last known position, if it's
                // not possible, then we go to the 0.0, 0.0 location
                LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                String bestProvider = locationManager.getBestProvider(new Criteria(), true);
                Location location = locationManager.getLastKnownLocation(bestProvider);
                if (location != null) {
                    latLng = new LatLng(location.getLatitude(), location.getLongitude());
                } else {
                    latLng = new LatLng(0, 0);
                }
            }
            updateCamera(latLng);
        }
    }
}

From source file:be.artoria.belfortapp.fragments.MapFragment.java

private GeoPoint getCurrentLocation() {
    // Get the location manager
    final LocationManager locationManager = (LocationManager) getActivity().getApplicationContext()
            .getSystemService(Context.LOCATION_SERVICE);
    // Define the criteria how to select the locatioin provider -> use
    // default//from w ww  .  j ava  2 s. c o  m
    final Criteria criteria = new Criteria();
    final String provider = locationManager.getBestProvider(criteria, false);
    final Location loc = locationManager.getLastKnownLocation(provider);

    if (loc != null) {
        return new GeoPoint(loc.getLatitude(), loc.getLongitude());
    } else {
        return new GeoPoint(DataManager.BELFORT_LAT, DataManager.BELFORT_LON);
    }
}