【问题标题】:How to Resume LocationServices to request location updates in onResume Method如何恢复 LocationServices 以在 onResume 方法中请求位置更新
【发布时间】:2016-02-20 21:49:09
【问题描述】:

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

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

2 我不知道如何在onResume 方法中恢复LocationServices.FusedLocationApi,因此一旦用户离开应用程序,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!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!********************************");
}

}

【问题讨论】:

  • 我编辑了我的 Activity 类,只显示与问题相关的代码。

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


【解决方案1】:

我认为你应该再打电话给

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

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

【讨论】:

  • 谢谢@Melvin Mauricio,我按照你的建议做了,但是应用程序在启动时崩溃了,奇怪的是 logcat 中没有显示错误。可以肯定的是,将LocationRequest 设为全局是否仅仅意味着在MainActivity 中声明LocationRequest request;
  • 首先检查你的 google api 客户端是否连接 googleApiclient.isConnected() 并且如果它是请求执行该方法
  • 你能帮我分解一下吗?我该怎么做?
  • 我需要整个 Activity 类
  • 我更新了我的问题以包括整个 Activity 类。很抱歉这么晚才回复。
【解决方案2】:

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

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

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

【讨论】:

  • 感谢您的评论。请您指出一些不一致的地方。我还是个新手,我需要我能得到的所有帮助。
【解决方案3】:

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

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

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

而且效果很好!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 2018-07-11
    • 2014-06-03
    • 1970-01-01
    相关资源
    最近更新 更多