如何恢复LocationServices以在onResume方法中请求位置更新

时间:2015-11-18 23:08:17

标签: android google-maps onresume location-services android-fusedlocation

我的应用使用Google Maps Api来显示用户的当前位置,除了两个问题外似乎工作正常:

1除非重新启动应用,否则用户的位置不会实时更新。

2我不知道如何在LocationServices.FusedLocationApi方法中恢复onResume,因此一旦用户离开应用,GPS就不会重启。

我尝试按照本网站上的教程和类似问题中的大部分建议(例如Where should I request location updates in A service?),但到目前为止我的案例没有任何效果。

这是我的代码:

public class MainActivity extends AppCompatActivity
implements GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener
{

private static final int ERROR_DIALOG_REQUEST = 9001;
GoogleMap mMap;

private GoogleApiClient mLocationClient;
private LocationListener mListener;
private View view;

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

    if (servicesOK()) { // If map is available, load it.
        setContentView(R.layout.activity_map);

        if (initMap()){
            mLocationClient = new GoogleApiClient.Builder(this)
                    .addApi(LocationServices.API)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this).build();
            mLocationClient.connect();

        } else {
            Toast.makeText(this, "Map not connected!", Toast.LENGTH_SHORT).show();
        }
    } else {
        setContentView(R.layout.activity_main);
    }
}

public boolean servicesOK (){
    // Checks if GooglePlayServices (Google Map) connection is established
    int isAvailable = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);

    if (isAvailable == ConnectionResult.SUCCESS) {
        return true;
    } else if (GooglePlayServicesUtil.isUserRecoverableError(isAvailable)) {
        Dialog dialog =
                GooglePlayServicesUtil.getErrorDialog(isAvailable, this, ERROR_DIALOG_REQUEST);
        dialog.show();
    } else {
        Toast.makeText(this, "Mapping unsuccessful!", Toast.LENGTH_SHORT).show();
    }
    return false;
}

private boolean initMap() {
    if (mMap == null) {
        SupportMapFragment mapFragment =
                (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mMap = mapFragment.getMap();
    }
    return (mMap != null);
}

private void gotoLocation(double lat, double lng) {
    LatLng latLng = new LatLng(lat, lng);
}

public void showCurrentLocation(MenuItem item) {
    Location currentLocation = LocationServices.FusedLocationApi
            .getLastLocation(mLocationClient);

    if (currentLocation == null) {
        Toast.makeText(this, "Couldn't connect to map!", Toast.LENGTH_SHORT).show();
        Log.d("Hello", "Couldn't connect to map" + "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!********************************");

    } else {
        LatLng latLng = new LatLng(
                currentLocation.getLatitude(),
                currentLocation.getLongitude()
        );
        CameraUpdate update = CameraUpdateFactory.newLatLngZoom(
                latLng, 15
        );
        mMap.animateCamera(update);
    }
}

@Override
public void onConnected(Bundle connectionHint) {
    // Executed when connection is successful
    Toast.makeText(this, "Map ready!", Toast.LENGTH_SHORT).show();

    Location currentLocation = LocationServices.FusedLocationApi
            .getLastLocation(mLocationClient);

    LatLng latLng1 = new LatLng(
            currentLocation.getLatitude(),
            currentLocation.getLongitude()
    );

    //Adds Marker when map is connected!
    MarkerOptions options = new MarkerOptions().position(latLng1).visible(true).title("Me!")              .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_VIOLET));
    mMap.addMarker(options);

    mListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            Toast.makeText(MainActivity.this,
            "Location changed!", Toast.LENGTH_SHORT).show();
            gotoLocation(location.getLatitude(), location.getLongitude());
        }
    };

        // Requests user's current location
    LocationRequest request = LocationRequest.create();
    request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    request.setInterval(10000); // TODO: 11/12/15 Change this to 90000 (90 secs)!!!!!!!!!!!!!
    request.setFastestInterval(3000); // TODO: 11/12/15 Change this to 60000 (60 secs)!!!!!!!!!
    LocationServices.FusedLocationApi.requestLocationUpdates(
            mLocationClient, request, mListener
    );
}

@Override
protected void onPause() { // Stops location updates
    super.onPause();
    LocationServices.FusedLocationApi.removeLocationUpdates(
            mLocationClient, mListener
    );
    Log.d("Hello", "The map has been paused!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!********************************");
}

@Override
protected void onResume() { // Resumes location updates
    super.onResume();
    Log.d("Hello", "The map has been resumed!!!!!!!!!!!!!!!!!********************************");

//Moves camera to user's current location!
        LocationRequest request = LocationRequest.create();
        request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        Location currentLocation = LocationServices.FusedLocationApi
                .getLastLocation(mLocationClient);
        if (currentLocation == null) {
            Toast.makeText(this, "Couldn't connect to map!", Toast.LENGTH_SHORT).show();
        } else {
            LatLng latLng = new LatLng(
                    currentLocation.getLatitude(),
                    currentLocation.getLongitude()
            );
            CameraUpdate update = CameraUpdateFactory.newLatLngZoom(
                    latLng, 15
            );
            mMap.animateCamera(update);
        }
}

@Override
public void onConnectionSuspended(int i) {
    // Executed when connection is stopped
    Log.d("Hello", "The connection was suspended!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!********************************");
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
// Executed when connection is unsuccessful
    Log.d("Hello", "The connection failed!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!********************************");
}

}

3 个答案:

答案 0 :(得分:2)

我想你应该再打电话给

 LocationServices.FusedLocationApi.requestLocationUpdates(
        mLocationClient, request, mListener);
在onResume()方法中

并使LocationRequest请求全局

答案 1 :(得分:1)

您根本没有在活动中启动LocationUpdates。在onConnected()中启动它。请参阅here

启动位置更新后,在onResume()中,您只需要检查GoogleApiClient是否已连接,以及requestedLocationUpdates是否已初始化并启动locationUpdates。见this

PS:你的代码也存在其他不一致之处,你应该阅读整本指南一次并准确理解这些方法。

答案 2 :(得分:0)

我终于使用this answer解决了这个问题。

我使用onResume()

而不是onRestart()(经过数周的努力后,它对我没用)
@Override
protected void onRestart(){
    super.onRestart();
    onConnected(Bundle.EMPTY);
}

它完美无缺!