Android LocationClient 클래스는 더 이상 사용되지 않지만 설명서에서 사용됩니다. 알 수 있습니다. 그러나 더 이상

의 문서를 LocationClient살펴보면 클래스가 더 이상 사용되지 않음을 알 수 있습니다.

그러나 더 이상 사용되지 않는 클래스는 문서에서 현재 위치를 얻기 위해 사용 됩니다 .

나는 이것이 약간 오도라고 생각하거나 잘못된 문서를보고 있습니까?



답변

다시 한 번 Google은 새로운 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"/>

참고 : 업데이트없이 마지막 위치 LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient)를 가져와야하는 경우 OnConnected에서 사용할 수 있습니다.


답변

일부 문서는 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);

답변

이것은 개발자 블로그 에서 다룬 것 같습니다 . LocationClient의 경우와 함께이 사용하는 거라고 LocationServices 다음에 우리를 인도 GeofencingApi .


답변

LocationClient가 제거되었습니다. GoogleApiClient는 Google Play 서비스 위치 API에 사용하는 API입니다.

일반적인 시나리오에 대한 샘플 코드가 여기 있으며 교육 클래스 더 빨리 업데이트됩니다 .


답변

설명서 업데이트 코드 에 따르면

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

    }
}

답변

코드에 간단히 추가하면됩니다.

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

        }
    });
  .
  .
  }

설명서 업데이트 코드 에 따르면