0

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

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

2 我不知道如何恢复LocationServices.FusedLocationApionResume因此一旦用户离开应用程序,GPS 不会重新启动。

我尝试遵循本网站上的教程和类似问题中的大多数建议(例如我应该在哪里请求 A 服务中的位置更新?),但到目前为止,我的案例没有任何效果。

这是我的代码:

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!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!********************************");
}

}

4

3 回答 3

2

我想你应该再打电话给

 LocationServices.FusedLocationApi.requestLocationUpdates(
        mLocationClient, request, mListener);

在 onResume() 方法中并使 LocationRequest 请求全局

于 2015-11-18T23:55:41.623 回答
1

您根本没有在活动中启动 LocationUpdates。在 onConnected() 中启动它。参考这里

开始位置更新后,在 onResume() 中,您只需要检查 GoogleApiClient 是否已连接以及 requestingLocationUpdates 是否已初始化,然后您就可以启动 locationUpdates。看到这个

PS:您的代码也有其他不一致之处,您可能应该阅读整个指南一次并准确理解这些方法。

于 2015-11-20T23:55:24.867 回答
0

我终于通过使用这个答案解决了这个问题。

而不是onResume()(经过数周的尝试后对我不起作用),我使用onRestart()

@Override
protected void onRestart(){
    super.onRestart();
    onConnected(Bundle.EMPTY);
}

而且效果很好!

于 2015-12-23T13:42:05.710 回答