简体   繁体   中英

How to get Android current location "only on demand" using Location Manager but without Location Listener?

My app does not need on-the-fly location updates. It needs the location only when (1)The app starts; (2)A specific activity/fragment is opened; (3)The user hits "get my location" button.

The criteria is: when demanded the location must come fast even if it is coarse with (if possible) minimum battery consumption. I plan to use a method along the lines of:

public void getLocation() {
        LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

        Location location = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);

        if(location != null) {
            //save the location to shared prefs to use when needed
            return;
        }

        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

        if(location != null) {
            //save the location to shared prefs to use when needed
            return;
        }

        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        if(location != null) {
            //save the location to shared prefs to use when needed
            return;
        }

        // if reached that point the location cannot be got!!
    }

The plan is to call that method every-time the app starts, or a specific page is activated, or user wants to get the current location. Unless those actions trigger a location update, the old location or no location is enough. Does this approach make sense? Can I do that without implementing Location Listener and/or calling the method "requestLocationUpdates()"? My concern is "getLastKnownLocation()" may not give the current location when called since I am not sure how often or at what conditions that "last known location" from a provider is updated.

Any suggestions and comments are highly appreciated.

Use the Following Code to get the Current and Last Known Location using Google Location Services API

//Global Variable
Location location;
public class MainActivity extends ActionBarActivity implements
    GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
    LocationListener {

   mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();

    mLocationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(10 * 1000)        // 10 seconds, in milliseconds
            .setFastestInterval(1 * 1000); // 1 second, in milliseconds

   @Override
protected void onResume() {
    super.onResume();
    mGoogleApiClient.connect();
}

@Override
protected void onPause() {
    super.onPause();
    if (mGoogleApiClient.isConnected()) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        mGoogleApiClient.disconnect();
    }
}

@Override
public void onConnected(Bundle bundle) {
    location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if (location == null) {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    } else {
        handleNewLocation(location);
    }
}

  @Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    if (connectionResult.hasResolution()) {
        try {
            // Start an Activity that tries to resolve the error
            connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
        } catch (IntentSender.SendIntentException e) {
            e.printStackTrace();
        }
    } else {
        Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
    }
}

AnyActivity.class

MainActivity main = new MainActivity();
Location location = main.location;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM