Android: LocationServices.FusedLocationApi.requestLocationUpdates продолжает работать и не возвращается

Я пытаюсь получить текущее местоположение пользователя, чтобы указать его на карте, поскольку это первый раз, когда эмулятор получает местоположение пользователя, LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient) возвращает нулевое местоположение. Затем я пытаюсь получить местоположение с помощью этого LocationServices.FusedLocationApi.requestLocationUpdates, однако, когда я отлаживаю приложение, приложение сообщает в окне отладки, что приложение работает, поэтому я предполагаю, что оно не может вернуть местоположение в функцию onLocationChanged (местоположение).

Когда я запускаю приложение без его отладки, оно выдает такие ошибки

08-25 02:44:06.988 2976-2985/com.example.bkoseoglu.findlocation D/dalvikvm: GC_FOR_ALLOC освобождено ‹1K, 10% свободно 13564K/14988K, пауза 21 мс, всего 21 мс

08-25 02:44:07.128 2976-3013/com.example.bkoseoglu.findlocation D/dalvikvm: GC_FOR_ALLOC освобождено 4228K, 37% свободно 9469K/14988K, пауза 5 мс, всего 5 мс

08-25 02:44:07.128 2976-3013/com.example.bkoseoglu.findlocation I/dalvikvm-heap: увеличить размер кучи (фрагментарный регистр) до 13,397 МБ для выделения 4 194 316 байт.

08-25 02:44:07.148 2976-3013/com.example.bkoseoglu.findlocation D/dalvikvm: GC_FOR_ALLOC освобождено ‹1K, 10% свободно 13564K/14988K, пауза 20 мс, всего 20 мс

Знаете ли вы, в чем может быть причина и как я могу получить местоположение onLocationChanged??? Я также копирую и вставляю приведенный ниже код, так как, возможно, что-то не так с настройками обновлений, интервалом или чем-то еще.

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,LocationListener {

@Override
public void onLocationChanged(Location location) {
    handleNewLocation(location);
}

private GoogleApiClient mGoogleApiClient;
public static final String TAG = MapsActivity.class.getSimpleName();
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private LocationRequest mLocationRequest;
private GoogleMap mMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //updateValuesFromBundle(savedInstanceState)
    setContentView(R.layout.activity_maps);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    // Create the LocationRequest object
    mLocationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(10 * 1000)        // 10 seconds, in milliseconds
            .setFastestInterval(1 * 1000); // 1 second, in milliseconds
}

/*private void updateValuesFromBundle(Bundle savedInstanceState) {
    if (savedInstanceState != null) {
        // Update the value of mRequestingLocationUpdates from the Bundle, and
        // make sure that the Start Updates and Stop Updates buttons are
        // correctly enabled or disabled.
        if (savedInstanceState.keySet().contains(REQUESTING_LOCATION_UPDATES_KEY)) {
            mRequestingLocationUpdates = savedInstanceState.getBoolean(
                    REQUESTING_LOCATION_UPDATES_KEY);
            setButtonsEnabledState();
        }

        // Update the value of mCurrentLocation from the Bundle and update the
        // UI to show the correct latitude and longitude.
        if (savedInstanceState.keySet().contains(LOCATION_KEY)) {
            // Since LOCATION_KEY was found in the Bundle, we can be sure that
            // mCurrentLocationis not null.
            mCurrentLocation = savedInstanceState.getParcelable(LOCATION_KEY);
        }

        // Update the value of mLastUpdateTime from the Bundle and update the UI.
        if (savedInstanceState.keySet().contains(LAST_UPDATED_TIME_STRING_KEY)) {
            mLastUpdateTime = savedInstanceState.getString(
                    LAST_UPDATED_TIME_STRING_KEY);
        }
        updateUI();
    }
}*/
/*public void onSaveInstanceState(Bundle savedInstanceState) {
    savedInstanceState.putBoolean(REQUESTING_LOCATION_UPDATES_KEY,
            mRequestingLocationUpdates);
    savedInstanceState.putParcelable(LOCATION_KEY, mCurrentLocation);
    savedInstanceState.putString(LAST_UPDATED_TIME_STRING_KEY, mLastUpdateTime);
    super.onSaveInstanceState(savedInstanceState);
}*/
protected void startLocationUpdates() {
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    if(CheckGps()) {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }
    else{
        Log.d("GPS NOT ENABLED ", "GPS NOT ENABLED ");
    }
}
/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    // Add a marker in Sydney and move the camera
    LatLng sydney = new LatLng(-34, 151);
    mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}



@Override
public void onConnected(@Nullable Bundle bundle) {

    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
            .addLocationRequest(mLocationRequest);

    PendingResult<LocationSettingsResult> result =
            LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient,
                    builder.build());
    result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
        @Override
        public void onResult(LocationSettingsResult result) {
            final Status status = result.getStatus();
            final LocationSettingsStates locationSettingsStates = result.getLocationSettingsStates();
            switch (status.getStatusCode()) {
                case LocationSettingsStatusCodes.SUCCESS:
                    // All location settings are satisfied. The client can
                    // initialize location requests here.
                    break;
                case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                    // Location settings are not satisfied, but this can be fixed
                    // by showing the user a dialog.
                    try {
                        // Show the dialog by calling startResolutionForResult(),
                        // and check the result in onActivityResult().
                        status.startResolutionForResult(
                                MapsActivity.this,
                                6);
                    } catch (IntentSender.SendIntentException e) {
                        // Ignore the error.
                    }
                    break;
                case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                    // Location settings are not satisfied. However, we have no way
                    // to fix the settings so we won't show the dialog.
                    break;
            }
        }
    });

    if (location == null) {
        startLocationUpdates();
    }
    else {
        handleNewLocation(location);
    };
}
public void handleNewLocation(Location location){
    Log.d(TAG, location.toString());

    double currentLatitude = location.getLatitude();
    double currentLongitude = location.getLongitude();
    LatLng latLng = new LatLng(currentLatitude, currentLongitude);

    MarkerOptions options = new MarkerOptions()
            .position(latLng)
            .title("I am here!");
    mMap.addMarker(options);
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}

@Override
public void onConnectionSuspended(int i) {
}

@Override
public void onConnectionFailed(@NonNull 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());
    }
}
@Override
protected void onResume() {
    super.onResume();
    //setUpMapIfNeeded();
    mGoogleApiClient.connect();
}
@Override
protected void onPause() {
    super.onPause();
    if (mGoogleApiClient.isConnected()) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        mGoogleApiClient.disconnect();
    }
}
boolean CheckGps(){
    LocationManager lm = (LocationManager)MapsActivity.this.getSystemService(MapsActivity.this.LOCATION_SERVICE);
    boolean gps_enabled = false;
    boolean network_enabled = false;

    try {
        gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    } catch(Exception ex) {}

    try {
        network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    } catch(Exception ex) {}

    if(!gps_enabled && !network_enabled) {
        return false;
    }
    else{
        return true;
    }
}
}

Спасибо.


person B.Koseoglu    schedule 25.08.2016    source источник
comment
импортировать android.content.IntentSender; импортировать android.content.pm.PackageManager; импортировать android.location.Location; импортировать android.location.LocationManager; импортировать android.support.annotation.NonNull; импортировать android.support.annotation.Nullable; импортировать android.support.v4.app.ActivityCompat; импортировать android.support.v4.app.FragmentActivity; импортировать android.os.Bundle; импортировать android.util.Log;   -  person B.Koseoglu    schedule 25.08.2016
comment
импортировать com.google.android.gms.common.ConnectionResult; импортировать com.google.android.gms.common.api.GoogleApiClient; импортировать com.google.android.gms.common.api.PendingResult; импортировать com.google.android.gms.common.api.ResultCallback; импортировать com.google.android.gms.common.api.Status; импортировать com.google.android.gms.location.LocationListener;   -  person B.Koseoglu    schedule 25.08.2016
comment
Это пакеты import com.google.android.gms.location.LocationRequest; импортировать com.google.android.gms.location.LocationServices; импортировать com.google.android.gms.location.LocationSettingsRequest; импортировать com.google.android.gms.location.LocationSettingsResult; импортировать com.google.android.gms.location.LocationSettingsStates; импортировать com.google.android.gms.location.LocationSettingsStatusCodes; импортировать com.google.android.gms.maps.CameraUpdateFactory; импортировать com.google.android.gms.maps.GoogleMap;   -  person B.Koseoglu    schedule 25.08.2016
comment
импортировать com.google.android.gms.maps.OnMapReadyCallback; импортировать com.google.android.gms.maps.SupportMapFragment; импортировать com.google.android.gms.maps.model.LatLng; импортировать com.google.android.gms.maps.model.MarkerOptions;   -  person B.Koseoglu    schedule 25.08.2016


Ответы (1)


Во-первых, я бы рекомендовал попробовать это на реальном устройстве, если это возможно. Если нет, убедитесь, что вы установили широту/долготу для своего эмулятора. Вот очень хорошее руководство о том, как это сделать эмулировать местоположение GPS в эмуляторе Android?

person Gaurav Sarma    schedule 25.08.2016
comment
Я исправил широту и длину эмулятора, но использовал командную строку, подключив telnet к эмулятору, но Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); по-прежнему возвращает местоположение с нулевым значением. - person B.Koseoglu; 26.08.2016
comment
@ B.Koseoglu вы все равно можете попробовать приложение на устройстве? - person Gaurav Sarma; 26.08.2016