How do I get the current GPS location programmatically in Android?

前端 未结 22 2664
梦谈多话
梦谈多话 2020-11-21 04:42

I need to get my current location using GPS programmatically. How can i achieve it?

22条回答
  •  再見小時候
    2020-11-21 05:03

    You need to use latest/newest

    GoogleApiClient Api

    Basically what you need to do is:

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

    Then

    @Override
        public void onConnected(Bundle connectionHint) {
            mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                    mGoogleApiClient);
            if (mLastLocation != null) {
                mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
                mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
            }
        }
    

    for the most accurate and reliable location. See my post here:

    https://stackoverflow.com/a/33599228/2644905

    Do not use LocationListener which is not accurate and has delayed response. To be honest this is easier to implement. Also read documentation: https://developers.google.com/android/reference/com/google/android/gms/common/api/GoogleApiClient

提交回复
热议问题