La clase Android LocationClient está obsoleta pero se usa en la documentación


Si vamos a través de la documentación de la LocationClient, podemos ver que la clase está en desuso.

Pero la clase obsoleta se usa en la documentación para obtener la ubicación actual.

Creo que esto es un poco engañoso o estoy mirando documentaciones incorrectas?

 146
Author: rink.attendant.6, 2014-07-07

5 answers

De nuevo Google ha lanzado una nueva API, pero no han actualizado la documentación: After Después de pasar algún tiempo tratando de averiguar cómo funciona lo conseguí, aquí tienes un ejemplo completo usando la nueva/última API de Servicio de ubicación... Disfruta desarrollando:)

import android.location.Location;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

public class MainActivity extends Activity implements
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

    private final String TAG = "MyAwesomeApp";

    private TextView mLocationView;

    private GoogleApiClient mGoogleApiClient;

    private LocationRequest mLocationRequest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mLocationView = new TextView(this);

        setContentView(mLocationView);

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

    @Override
    protected void onStart() {
        super.onStart();
        // Connect the client.
        mGoogleApiClient.connect();
    }

    @Override
    protected void onStop() {
        // Disconnecting the client invalidates it.
        mGoogleApiClient.disconnect();
        super.onStop();
    }

    @Override
    public void onConnected(Bundle bundle) {

        mLocationRequest = LocationRequest.create();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(1000); // Update location every second

        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);
    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.i(TAG, "GoogleApiClient connection has been suspend");
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.i(TAG, "GoogleApiClient connection has failed");
    }

    @Override
    public void onLocationChanged(Location location) {
        mLocationView.setText("Location received: " + location.toString());
    }
}

Y no olvides agregar estos permisos a tu AndroidManifest.archivo xml:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

Nota: si solo necesita obtener la última ubicación (sin actualizaciones), puede usar LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient) desde onConnected

 270
Author: Diego Palomar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-08 23:24:46

Parte de la documentación es antigua en Google (algunos ejemplos que mencionaste todavía usan el obsoleto LocationClient). Tienes que usar el nuevo GoogleApiClient como se describe en los ejemplos de Servicios de localización:

private GoogleApiClient mGoogleApiClient;

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

Y cuando el nuevo cliente está conectado, puede usar la api de ubicación fusionada, por ejemplo, de la siguiente manera:

LocationServices.FusedLocationApi.requestLocationUpdates(theNewClient, 
    locationRequest, locationListener);
 22
Author: paularius,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-04 11:21:13

Parece que esto fue cubierto en el blog de desarrolladores . Para LocationClient, usarías esto junto con LocationServicesque luego nos lleva a GeofencingApi.

 4
Author: Sofi Software LLC,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-11 01:12:59

Se elimina LocationClient. GoogleApiClient es una api que se puede usar para las API de ubicación de Google Play Services.

El código de ejemplo para los escenarios comunes es aquí y las clases de entrenamiento se actualizaron con más próximamente.

 3
Author: PaulR,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-17 06:08:32

De acuerdo con el código de actualización de la documentación ..

package iwannado.com.myapplicationforsha1key;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Geocoder;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.identity.intents.Address;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import java.io.IOException;
import java.util.List;

public class MapWithMapViewActivity extends AppCompatActivity implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
    private static final String TAG = MapWithMapViewActivity.class.getCanonicalName();


    private GoogleMap mMap = null;
    private MapView mMapView = null;

    private EditText loatcationEditText = null;

    private GoogleApiClient mGoogleApiClient = null;
    private Location mLocationRequest = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map_with_map_view);
        loatcationEditText = (EditText) findViewById(R.id.loatcation_edit_text);
        mMapView = (MapView) findViewById(R.id.mapView);
        /*
        * The method is used to create mapView
        * */
        mMapView.onCreate(savedInstanceState);
        /*
        *The method Return Google map
        * */
        mMapView.getMapAsync(this);

        gotoCurrentLoactionGooglePlayService();
    }

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


    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mMapView.onLowMemory();
    }

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

    @Override
    protected void onStop() {
        super.onStop();
        mGoogleApiClient.disconnect();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }


    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;



    }



    private void gotoCurrentLoactionGooglePlayService() {
        /*working with new google api for laction..
http://stackoverflow.com/a/25173057
* */
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
    }



    @Override
    public void onConnected(@Nullable Bundle bundle) {
/*
* Follow this documentation.. https://developer.android.com/training/location/retrieve-current.html
*
* Please add Runtime permission here for android 6
* */
        mLocationRequest = LocationServices.FusedLocationApi.getLastLocation(
                mGoogleApiClient);
        if (mLocationRequest != null) {

           LatLng latLng = new LatLng(mLocationRequest.getLatitude(),mLocationRequest.getLongitude());
        mMap.addMarker(new MarkerOptions().position(latLng).title("Programmatically Current Loaction"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
            Toast.makeText(this,"getLatitude() = "+String.valueOf(mLocationRequest.getLatitude())+"\n getLongitude() = "+String.valueOf(mLocationRequest.getLongitude()),Toast.LENGTH_LONG).show();

        }
    }


    @Override
    public void onConnectionSuspended(int i) {
        Log.i(TAG, "GoogleApiClient connection has been suspend");
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.i(TAG, "GoogleApiClient connection has failed");
    }

    @Override
    public void onLocationChanged(Location location) {


        Toast.makeText(this,"Location received: " + location.toString(),Toast.LENGTH_LONG).show();

    }
}
 0
Author: Java coder,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-29 12:11:54