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:edu.mit.mobile.android.locast.casts.LocatableListWithMap.java

/**
 * Gets the last-known location and updates with that.
 *//*w w  w. j  a  va  2  s .  c  o  m*/
private void updateLocation() {
    final LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
    final String provider = lm.getBestProvider(new Criteria(), true);
    if (provider == null) {
        Toast.makeText(this, getString(R.string.error_no_providers), Toast.LENGTH_LONG).show();
        finish();
        return;
    }

    final Location loc = lm.getLastKnownLocation(provider);
    if (loc != null) {
        updateLocation(loc);
    } else {
        Toast.makeText(this, R.string.notice_finding_your_location, Toast.LENGTH_LONG).show();
        setRefreshing(true);
    }
    mLastLocation = loc;
}

From source file:com.facebook.react.modules.location.LocationModule.java

/**
 * Get the current position. This can return almost immediately if the location is cached or
 * request an update, which might take a while.
 *
 * @param options map containing optional arguments: timeout (millis), maximumAge (millis) and
 *        highAccuracy (boolean)//  w w w  .jav  a 2 s . c  o  m
 */
@ReactMethod
public void getCurrentPosition(ReadableMap options, final Callback success, Callback error) {
    LocationOptions locationOptions = LocationOptions.fromReactMap(options);

    try {
        LocationManager locationManager = (LocationManager) getReactApplicationContext()
                .getSystemService(Context.LOCATION_SERVICE);
        String provider = getValidProvider(locationManager, locationOptions.highAccuracy);
        if (provider == null) {
            error.invoke(PositionError.buildError(PositionError.POSITION_UNAVAILABLE,
                    "No location provider available."));
            return;
        }
        Location location = locationManager.getLastKnownLocation(provider);
        if (location != null
                && (SystemClock.currentTimeMillis() - location.getTime()) < locationOptions.maximumAge) {
            success.invoke(locationToMap(location));
            return;
        }

        new SingleUpdateRequest(locationManager, provider, locationOptions.timeout, success, error)
                .invoke(location);
    } catch (SecurityException e) {
        throwLocationPermissionMissing(e);
    }
}

From source file:fiser.Activities.MainActivity.java

private void listaRecargar(boolean cercanos) {
    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    sitioList.clear();/*from ww w  .j  a  va2s. c om*/
    if (!cercanos) {
        for (Sitio sitio : Sitio.getSitio(this))
            sitioList.add(sitio);
    } else {
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String provider = locationManager.getBestProvider(criteria, true);
        if (ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            for (Sitio sitio : Sitio.getSitio(this))
                sitioList.add(sitio);
        } else {
            Location location = locationManager.getLastKnownLocation(provider);
            for (Sitio sitio : Sitio.getSitio(this)) {
                Location loc = new Location("temp");
                loc.setLatitude(sitio.latitud);
                loc.setLongitude(sitio.longitud);
                float distance = location.distanceTo(loc);
                int cercaniaMinimaInt = sharedPref.getInt(getString(R.string.cercaniaMinima),
                        getResources().getInteger(R.integer.cercaniaMinimaDefault));
                if (cercaniaMinimaInt * 1000 > distance)
                    sitioList.add(sitio);
            }
        }
    }
    adapter.notifyDataSetChanged();
}

From source file:com.findcab.driver.activity.Signup.java

private void initView() {
    context = this;
    back = (Button) findViewById(R.id.back);
    back.setOnClickListener(this);
    start = (Button) findViewById(R.id.start);
    start.setOnClickListener(this);

    edit_name = (EditText) findViewById(R.id.name);
    edit_mobile = (EditText) findViewById(R.id.mobile);
    edit_password = (EditText) findViewById(R.id.password);

    checkBox = (CheckBox) findViewById(R.id.checkBox);

    item = (TextView) findViewById(R.id.item);
    item.setOnClickListener(this);

    if (initGPS()) {

        LocationManager locationManager;
        String serviceName = Context.LOCATION_SERVICE;
        locationManager = (LocationManager) this.getSystemService(serviceName);
        // ?/*from   w  w w  .j a  v a  2  s.co m*/
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(true);
        criteria.setPowerRequirement(Criteria.POWER_LOW);

        String provider = locationManager.getBestProvider(criteria, true);
        location = locationManager.getLastKnownLocation(provider);
        if (location != null) {
            lat = location.getLatitude();
            lng = location.getLongitude();
        }
    }
}

From source file:system.info.reader.java

public String refresh() {
    //wifi/*from  ww w .  j  a  v  a2s .c o  m*/
    WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    if ((wifiInfo != null) && (wifiInfo.getMacAddress() != null))
        Properties.setInfo((String) propertyItems[4], wifiInfo.getMacAddress());
    else
        Properties.setInfo((String) propertyItems[4], "not avaiable");

    //String tmpsdcard = runCmd("df", "");
    //if (tmpsdcard != null) result += tmpsdcard + "\n\n";

    //setMap("dpi", dpi);

    //location
    LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
    List ll = lm.getProviders(true);
    Boolean foundLoc = false;
    for (int i = 0; i < ll.size(); i++) {
        Location lo = lm.getLastKnownLocation((String) ll.get(i));
        if (lo != null) {
            Properties.setInfo((String) propertyItems[3], lo.getLatitude() + ":" + lo.getLongitude());
            foundLoc = true;
            break;
        }
    }
    if (!foundLoc)
        Properties.setInfo((String) propertyItems[3], getString(R.string.locationHint));

    ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    List serviceList = am.getRunningServices(10000);
    serviceInfo = "";
    for (int i = 0; i < serviceList.size(); i++) {
        RunningServiceInfo rs = (RunningServiceInfo) serviceList.get(i);
        serviceInfo += rs.service.flattenToShortString() + "\n";
    }
    //result += getString(R.string.nService) + serviceList.size() + "\n";//service number

    psInfo = "";
    List appList = am.getRunningAppProcesses();
    for (int i = 0; i < appList.size(); i++) {
        RunningAppProcessInfo as = (RunningAppProcessInfo) appList.get(i);
        psInfo += as.processName + "\n";
    }
    //result += getString(R.string.nProcess) + appList.size() + "\n";//process number

    taskInfo = "";
    List taskList = am.getRunningTasks(10000);
    for (int i = 0; i < taskList.size(); i++) {
        RunningTaskInfo ts = (RunningTaskInfo) taskList.get(i);
        taskInfo += ts.baseActivity.flattenToShortString() + "\n";
    }
    //result += getString(R.string.nTask) + taskList.size() + "\n\n";//task number

    //result += getString(R.string.nProcess) + runCmd("ps", "") + "\n";//process number

    //setMap(getString(R.string.nApk), nApk);

    //send message to let view redraw.
    Message msg = mRedrawHandler.obtainMessage();
    mRedrawHandler.sendMessage(msg);
    //properListItemAdapter.notifyDataSetChanged();//no use?

    Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    vibrator.vibrate(400);
    return "";
}

From source file:org.hfoss.posit.android.functionplugin.reminder.SetReminder.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Set the transparent blank screen as a background for dialogs
    setContentView(R.layout.blank_screen);

    // Exit the Activity if the proper settings are not enabled
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    boolean allowReminder = prefs.getBoolean("allowReminderKey", true);
    boolean allowGeoTag = prefs.getBoolean("geotagKey", true);
    // If the user allows, set the "Set Reminder" menu option
    if (!allowReminder || !allowGeoTag) {
        Toast.makeText(this, "Sorry. Geotagging and Allow Reminder settings must "
                + " be enabled to run the Set Reminder Activity.", Toast.LENGTH_LONG).show();
        finish();/*from   w ww  . j a  v a2s . com*/
    }

    mDbEntries = getIntent().getParcelableExtra("DbEntries");

    dateSetPressed = false;

    // Get intent passed in from FindActivity
    Bundle bundle = getIntent().getExtras();
    date = bundle.getString("Date");

    // Initialize variables for Date Picker Dialog
    year = date.substring(0, 4);
    month = date.substring(5, 7);
    day = date.substring(8, 10);

    // Initialize variables for longitude and latitude      
    findsLongitude = bundle.getDouble("FindsLongitude");
    findsLatitude = bundle.getDouble("FindsLatitude");

    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    Location netLocation = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    Location gpsLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    Location loc = null;

    if (gpsLocation != null) {
        loc = gpsLocation;
    } else {
        loc = netLocation;
    }
    if (loc != null) {
        currentLongitude = loc.getLongitude();
        currentLatitude = loc.getLatitude();
    }

    showDatePickerDialog();
}

From source file:org.openpilot_nonag.androidgcs.fragments.Map.java

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

    //disable the screen from turning off
    Log.d(TAG, "*** onCreateView");

    this.getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    // inflate and return the layout
    View v = inflater.inflate(R.layout.map_fragment, container, false);

    //      final Button buttonApply = (Button) v.findViewById(R.id.applyBtn);
    //      buttonApply.setOnClickListener(new View.OnClickListener() {
    //            public void onClick(View v) {
    //               updateObject(homeLocationObject.getObjID(),homeLocationObject.getInstID());
    //            }
    //        });
    //      buttonApply.setEnabled(false);
    //      // w ww .  j a v a2  s. c om
    //      final Button buttonSave = (Button) v.findViewById(R.id.saveBtn);
    //      buttonSave.setOnClickListener(new View.OnClickListener() {
    //            public void onClick(View v) {
    //               saveObject(homeLocationObject);
    //            }
    //        });
    //      buttonSave.setEnabled(false);

    mapView = (MapView) v.findViewById(R.id.map_view_fragment);
    mapView.onCreate(savedInstanceState);

    // get map type from preferences
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());

    int map_type = Integer.decode(prefs.getString("map_type", "1"));

    // Needs to call MapsInitializer before doing any CameraUpdateFactory
    // calls
    MapsInitializer.initialize(getActivity());

    // something wrong *here* (only on versions with out Google Play
    // Services) need to check instead of crashing.
    // should take care of this
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());

    if (status == ConnectionResult.SUCCESS) {

        // Gets to GoogleMap from the MapView and does initialization stuff
        mMap = mapView.getMap();
        mMap.getUiSettings().setMyLocationButtonEnabled(true);
        mMap.setIndoorEnabled(true);
        mMap.setMyLocationEnabled(true);
        mMap.setOnMyLocationChangeListener(this);

        switch (map_type) {
        case 0:
            mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
            mMap.getUiSettings().setIndoorLevelPickerEnabled(true);

            break;
        case 1:
            mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
            mMap.getUiSettings().setIndoorLevelPickerEnabled(true);
            break;
        case 2:
            mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
            break;
        case 3:
            mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
            break;
        }

        UAVpathLine = mMap.addPolyline(new PolylineOptions().width(5).color(Color.WHITE));
        UAVpathLine.setPoints(UAVpathPoints);
        NEDUAVpathLine = mMap.addPolyline(new PolylineOptions().width(5).color(Color.RED));
        NEDUAVpathLine.setPoints(NEDUAVpathPoints);
        TabletpathLine = mMap.addPolyline(new PolylineOptions().width(5).color(Color.BLUE));
        TabletpathLine.setPoints(TabletpathPoints);

        registerForContextMenu(mapView);
        //         mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
        //            
        //            @Override
        //            public void onMapClick(LatLng arg0) {
        //               // TODO Auto-generated method stub
        //               Log.d(TAG, "Simple Click");
        //               
        //            }
        //         });

        mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
            @Override
            public void onMapLongClick(LatLng arg0) {
                Log.d(TAG, "Long Click");
                //getView().showContextMenu();
                mapView.showContextMenu();
                touchLocation = arg0;
            }
        });

        LocationManager locationManager = (LocationManager) getActivity()
                .getSystemService(Context.LOCATION_SERVICE);
        Location currentLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (currentLocation == null) {
            currentLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        }
        LatLng currentLatLng = new LatLng(0, 0);
        if (currentLocation != null) {
            currentLatLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
        }
        // zoom to cuurent location
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLatLng, 17));

    } else {
        Toast.makeText(getActivity(), "Google Play Services are not enabled.", Toast.LENGTH_SHORT).show();
    }

    return v;

}

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

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sample_map);

    mLatitude = (TextView) findViewById(R.id.latitude);
    mAccuracy = (TextView) findViewById(R.id.accuracy);
    mLongitude = (TextView) findViewById(R.id.longitude);

    mProvider = (TextView) findViewById(R.id.t01);

    mHandler = new Handler();

    // mApp = (ApplicationClass) getApplication();
    // mApp.setOnNotifiedMessageListener(mNotifiedMessageListener);
    // mLocationManager = new LocationServiceManager(getApplication());

    upReceiver = new UpdateReceiver();
    intentFilter = new IntentFilter();
    intentFilter.addAction("UPDATE_ACTION");
    registerReceiver(upReceiver, intentFilter);

    upReceiver.registerHandler(updateHandler);

    // ?/*w  w w. j a v  a2 s  .com*/
    Button setParamButton = (Button) findViewById(R.id.param);
    setParamButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            mGeoFenceManager = new GeoFenceManager(MainActivity.this);
            HashMap<String, Object> defaultMap = new HashMap<String, Object>();
            {
                defaultMap.put(GeoFenceManager.REQUEST_PARAM_KEY_CLIENTID, "JSZ3a03eb052f46|E7Tg6");
                defaultMap.put(GeoFenceManager.REQUEST_PARAM_KEY_TMID, "t1000_1");
                defaultMap.put(GeoFenceManager.REQUEST_PARAM_KEY_SECRET, "eNphiW-zYeDhnj37IL86bJeijmA");
                defaultMap.put(GeoFenceManager.REQUEST_PARAM_KEY_TNTP, "1");
                defaultMap.put(GeoFenceManager.REQUEST_PARAM_KEY_TATP, "1");
                defaultMap.put(GeoFenceManager.REQUEST_PARAM_KEY_NCURL,
                        "https://test-mlp.its-mo.com/mlp/v1_0/request/SearchNotifyConditionList.php");
                defaultMap.put(GeoFenceManager.REQUEST_PARAM_KEY_AIURL,
                        "https://test-mlp.its-mo.com/mlp/v1_0/request/SearchAreaInfoList.php");
                defaultMap.put("SAVE_INTERVAL", "2");
            }

            int result = mGeoFenceManager.setParams(defaultMap, 1);
            if (result == GeoFenceManager.SET_PARAMS_RESULT_CODE_SUCCESS) {
                Toast.makeText(MainActivity.this, "SET_PARAMS_RESULT_CODE_SUCCESS", Toast.LENGTH_LONG).show();
            } else if (result == GeoFenceManager.SET_PARAMS_RESULT_CODE_NO_REQUIRED) {
                Toast.makeText(MainActivity.this, "SET_PARAMS_RESULT_CODE_NO_REQUIRED", Toast.LENGTH_LONG)
                        .show();
            }
        }
    });

    // Area
    Button updateButton = (Button) findViewById(R.id.update);
    updateButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            int updateAreaInfomation = mGeoFenceManager.updateAreaInfomation();
            Toast.makeText(MainActivity.this, "updateAreaInfomation = " + updateAreaInfomation,
                    Toast.LENGTH_LONG).show();
            // UpdateAreaAsync areaAsync = new
            // UpdateAreaAsync(MainActivity.this, mGeoFenceManager);
            // areaAsync.execute();
        }
    });
    // GPS???
    Button gpsButton = (Button) findViewById(R.id.gps_button);
    gpsButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            LocationServiceManager locationServiceManager = new LocationServiceManager(MainActivity.this);
            locationServiceManager.startLocationService();
        }
    });

    // Google Play Services???????
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

    // Showing status
    if (status != ConnectionResult.SUCCESS) {
        // Google Play Services ?????
        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
        dialog.show();

    } else {
        // Google Play Services ???
        // activity_main.xml?SupportMapFragment????
        SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

        // fragment?GoogleMap object?
        gMap = fm.getMap();

        // Google Map?MyLocation???
        gMap.setMyLocationEnabled(true);
        gMap.setIndoorEnabled(true);
        gMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        gMap.setTrafficEnabled(true);

        // ?LOCATION_SERVICE?LocationManager object?
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        // retrieve provider?criteria object?
        Criteria criteria = new Criteria();

        // Best provider?????
        String provider = locationManager.getBestProvider(criteria, true);

        // ???
        Location location = locationManager.getLastKnownLocation(provider);

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

    }

}

From source file:android.melbournehistorymap.MapsActivity.java

@Override
public void onRestart() {
    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    String locationProvider = LocationManager.GPS_PROVIDER;
    Location mLastLocation = locationManager.getLastKnownLocation(locationProvider);

    double lat = mLastLocation.getLatitude();
    double lng = mLastLocation.getLongitude();
    final int radius;
    int zoom;// w ww  .j  a v a 2 s . c om

    //build current location
    LatLng currentLocation = new LatLng(lat, lng);

    if (MELBOURNE.contains(currentLocation)) {
        mMap.getUiSettings().setMyLocationButtonEnabled(true);
        zoom = 17;
    } else {
        mMap.getUiSettings().setMyLocationButtonEnabled(false);
        lat = -37.81161508043379;
        lng = 144.9647320434451;
        zoom = 15;
        currentLocation = new LatLng(lat, lng);
    }

    CameraPosition cameraPosition = new CameraPosition.Builder().target(currentLocation) // Sets the center of the map to location user
            .zoom(zoom) // Sets the zoom
            .bearing(0) // Sets the orientation of the camera to east
            .tilt(25) // Sets the tilt of the camera to 30 degrees
            .build(); // Creates a CameraPosition from the builder

    //Animate user to map location, if in Melbourne or outside of Melbourne bounds
    mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition),
            new GoogleMap.CancelableCallback() {
                @Override
                public void onFinish() {
                    updateMap();
                }

                @Override
                public void onCancel() {

                }
            });

    updateMap();
    super.onRestart();
}

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

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    textview = (TextView) findViewById(R.id.tv_location);

    // Google Play Services???????
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

    // Showing status
    if (status != ConnectionResult.SUCCESS) {
        // Google Play Services ?????
        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
        dialog.show();// w w  w .ja v  a  2 s.  c  o m

    } else {
        // Google Play Services ???
        // activity_main.xml?SupportMapFragment????
        SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

        // fragment?GoogleMap object?
        gMap = fm.getMap();

        // Google Map?MyLocation???
        gMap.setMyLocationEnabled(true);
        gMap.setIndoorEnabled(true);
        gMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        gMap.setTrafficEnabled(true);

        // ?LOCATION_SERVICE?LocationManager object?
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        // retrieve provider?criteria object?
        Criteria criteria = new Criteria();

        // Best provider?????
        String provider = locationManager.getBestProvider(criteria, true);

        //provider??????????????
        if (provider != null) {
            Toast.makeText(this, provider + "???", Toast.LENGTH_LONG).show();

            Log.d("app", "the best provider is " + provider);
            // ???
            Location location = locationManager.getLastKnownLocation(provider);

            if (location != null) {
                onLocationChanged(location);
            }
            locationManager.requestLocationUpdates(provider, 20000, 0, this);
        } else { //GPS?????????
            Toast.makeText(this, "????????", Toast.LENGTH_LONG).show();
        }
    }

}