Android LocationClient类已弃用,但在文档中使用

时间:2014-07-07 13:40:13

标签: android

如果我们查看LocationClient的文档,我们可以看到该类已被弃用。

但已弃用的类用于documentation to get the current location

我认为这有点误导,或者我在查看不正确的文件?

6 个答案:

答案 0 :(得分:271)

谷歌再次发布了一个新的API,但他们没有更新文档:$花了一些时间试图弄清楚它是如何工作的我得到了它,在这里你有一个使用新的/最新的位置服务API的完整示例。 ..享受发展:)

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());
    }
}

并且不要忘记将此权限添加到AndroidManifest.xml文件中:

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

注意:如果您只需要获取最后一个位置(没有更新),则可以使用OnConnected中的LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient)

答案 1 :(得分:22)

Google中的一些文档已经过时(您提到的一些示例仍然使用已弃用的LocationClient)。 您必须使用位置服务示例中描述的新GoogleApiClient:

private GoogleApiClient mGoogleApiClient;

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

当连接新客户端时,您可以使用融合位置api,例如:

LocationServices.FusedLocationApi.requestLocationUpdates(theNewClient, 
    locationRequest, locationListener);

答案 2 :(得分:4)

developer blog似乎涵盖了这一点。对于LocationClient,您可以将其与LocationServices结合使用,然后引导我们GeofencingApi

答案 3 :(得分:3)

删除了LocationClient。 GoogleApiClient可用于Google Play服务位置API。

常见方案的示例代码为here,培训类were updated即将推出更多。

答案 4 :(得分:0)

根据documentation更新代码..

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();

    }
}

答案 5 :(得分:0)

您只需将其添加到代码中,

private FusedLocationProviderClient mFusedLocationClient;
private Location mLastLocation;

 oncreate(){
  .
  .
  FusedLocationProviderClient mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
   if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
    }
    mFusedLocationClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
        @Override
        public void onSuccess(Location location) {
            mLastLocation =location;
            if (mLastLocation!= null) {
                LogUtils.logE(TAG, "Lat: " + mLastLocation.getLatitude() + "Long: " + mLastLocation.getLongitude());
            }

        }
    });
  .
  .
  }

根据文档更新代码。