简体   繁体   English

使用 Google 地图 API 在 Android 中查找设备当前位置的纬度和经度值

[英]Finding the latitude and longitude values for the device's current location in Android with Google Maps API

So there are many similar questions asked based on this, and I have also got a working solution.因此,基于此提出了许多类似的问题,我也得到了一个可行的解决方案。 However, this seems to only work on my physical Android device.但是,这似乎只适用于我的物理 Android 设备。 If I were to use it with the emulator, the method returns a null value and I don't know why.如果我将它与模拟器一起使用,该方法会返回 null 值,我不知道为什么。 Many sources mention that there is a better alternative to the code that I am currently using but they don't mention what/how exactly.许多消息来源提到我目前使用的代码有更好的替代方案,但他们没有提到具体是什么/如何。 This is the code that I am using to get the current location of my device:这是我用来获取设备当前位置的代码:

@SuppressWarnings("MissingPermission")
    private LatLng getCurrentLocation() {
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        String locationProvider = LocationManager.NETWORK_PROVIDER;
        assert locationManager != null;
        android.location.Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
        return new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
    }

I also don't like the fact that I have to suppress warnings.我也不喜欢我必须压制警告的事实。 Sources that I have looked at include:我看过的资料包括:

https://developer.android.com/training/location/retrieve-current.html#java https://developer.android.com/training/location/retrieve-current.html#java

What is the simplest and most robust way to get the user's current location on Android? 在 Android 上获取用户当前位置的最简单、最可靠的方法是什么?

The first one doesn't work, I get a null value.第一个不起作用,我得到一个 null 值。 The second one looks overly complicated for a simple result that I am seeking.对于我正在寻求的简单结果,第二个看起来过于复杂。

This code works just fine in one of my projects:这段代码在我的一个项目中运行良好:

public class LocationManager {
        private static LocationManager requestManager;
        private FusedLocationProviderClient mLocationProviderClient;
        private Location mLocation;
        private Location mMyCurrentLocation;
        private locationSuccessListener mListener;

    public Location getLocation() {
        return mLocation;
    }

    public void setLocation(Location location) {
        mLocation = location;
    }

    private LocationManager(FusedLocationProviderClient fusedLocationProviderClient) {
        this.mLocationProviderClient = fusedLocationProviderClient;
    }

    public static LocationManager createInstance(FusedLocationProviderClient fusedLocationProviderClient) {
        if (requestManager != null) {
            return requestManager;
        } else {
            return requestManager = new LocationManager(fusedLocationProviderClient);
        }
    }

    public static LocationManager getInstance() {
        return requestManager;
    }

    public void setLocation(Activity activity) {
        mListener = (locationSuccessListener) activity;
        LocationCallback callback = new LocationCallback();
        LocationRequest locationRequest = new LocationRequest();
        Task<Void> r = mLocationProviderClient.requestLocationUpdates(locationRequest, callback, Looper.getMainLooper());
        r.addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                mLocationProviderClient.getLastLocation().addOnSuccessListener(activity, new OnSuccessListener<Location>() {
                    @Override
                    public void onSuccess(Location location) {
                        mMyCurrentLocation = location;
                        mLocation = location;
                        if (location != null) {
                            mListener.onLocationReceived();
                            mLocationProviderClient.removeLocationUpdates(callback);
                        }
                    }
                });
            }
        });


    }

    public Location getMyCurrentLocation() {
        return mMyCurrentLocation;
    }


    public interface locationSuccessListener {
        void onLocationReceived();
    }

You need to do something like that:你需要做这样的事情:

public class PlacesActivity extends SingleFragmentActivity implements NavigationView.OnNavigationItemSelectedListener, LocationManager.locationSuccessListener

and then in your activity you will get this:然后在你的活动中你会得到这个:

@Override
    public void onLocationReceived() {
         Location l = LocationManager.getInstance().getMyCurrentLocation();
             if (l==null){
                 Toast.makeText(this, "unable to get location", Toast.LENGTH_SHORT).show();
                 
             }
    }

to get permission you suppose to do something like this:要获得许可,您应该执行以下操作:

if (ContextCompat.checkSelfPermission(Objects.requireNonNull(getActivity()), Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(),
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    0);
            

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

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