简体   繁体   English

如何在不跟踪的情况下仅获取用户位置一次?

[英]How to get user location only once without tracking?

In my android app, I need to gt the user location when he clicks a button.在我的 android 应用程序中,当他单击按钮时,我需要 gt 用户位置。 I do not need to receive continuous updates on his location however.但是,我不需要接收有关他位置的持续更新。

I searched through a few questions on stackoverflow, but the answers are 2-3 years old, so I was wondering, as on the Android SDK now, what is the best way to do it.我在 stackoverflow 上搜索了几个问题,但答案是 2-3 年前的,所以我想知道,就像现在在 Android SDK 上一样,最好的方法是什么。

Also, I would like not to get null in the location if possible.另外,如果可能的话,我不想在该位置获得null

Thanks in advance.提前致谢。

UPDATE September 23, 2020 2020 年 9 月 23 日更新

Change log of version 17.1.0 mentions a new way to get current location: 版本 17.1.0 的更改日志提到了一种获取当前位置的新方法:

FusedLocationProviderClient.getCurrentLocation()

A single fresh location will be returned if the device location can be determined within reasonable time (tens of seconds), otherwise null will be returned.如果可以在合理的时间(数十秒)内确定设备位置,则将返回单个新位置,否则将返回 null。 This method may return locations that are a few seconds old, but never returns much older locations.此方法可能会返回几秒钟前的位置,但永远不会返回更旧的位置。 This is suitable for foreground applications that need a single fresh current location.这适用于需要单个新当前位置的前台应用程序。

Documentation: https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient#getCurrentLocation(int,%20com.google.android.gms.tasks.CancellationToken)文档: https : //developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient#getCurrentLocation(int,%20com.google.android.gms.tasks.CancellationToken)

Example of usage:用法示例:

val cancellationTokenSource = CancellationTokenSource()
fusedLocationProviderClient.getCurrentLocation(LocationRequest.PRIORITY_HIGH_ACCURACY, cancellationTokenSource.token)

// onStop or whenever you want to cancel the request
cancellationTokenSource.cancel()

Old Answer旧答案

You can use setNumUpdates method and pass the value 1. example:您可以使用setNumUpdates方法并传递值 1。示例:

mLocationRequest = new LocationRequest();
mLocationRequest.setNumUpdates(1);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

By default locations are continuously updated until the request is explicitly removed, however you can optionally request a set number of updates.默认情况下,位置会持续更新,直到请求被明确删除,但是您可以选择请求一定数量的更新。 For example, if your application only needs a single fresh location, then call this method with a value of 1 before passing the request to the location client.例如,如果您的应用程序只需要一个新位置,则在将请求传递给位置客户端之前,使用值为 1 调用此方法。

https://developers.google.com/android/reference/com/google/android/gms/location/LocationRequest.html#setNumUpdates(int) https://developers.google.com/android/reference/com/google/android/gms/location/LocationRequest.html#setNumUpdates(int)

Android introduce Fused Location in last I/O Summit, Fused location provide you more reliable and accurate location with the best available provider. Android 在上一届 I/O 峰会上引入了 Fused Location,Fused location 为您提供更可靠、更准确的位置以及最好的可用提供商。

import android.location.Location;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
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 AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {


    TextView txtOutputLat, txtOutputLon;
    Location mLastLocation;
    private GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;
    String lat, lon;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        GoogleApiClient();
    }


    @Override
    public void onConnected(Bundle bundle) {


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

        //use if you want location update
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,              mLocationRequest, this);

        // here you get current location
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                                                                          mGoogleApiClient);
        if (mLastLocation != null) {
            lat = String.valueOf(mLastLocation.getLatitude());
            lon = String.valueOf(mLastLocation.getLongitude());

        }

    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onLocationChanged(Location location) {
        lat = String.valueOf(location.getLatitude());
        lon = String.valueOf(location.getLongitude());

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        GoogleApiClient();
    }

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


    }

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

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


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



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


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

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



 public class MainActivity extends ActionBarActivity implements
    ConnectionCallbacks, OnConnectionFailedListener {

@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 further reference see here如需进一步参考, 请参见此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM