Android getLastKnownLocation 返回 null

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20438627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 02:51:31  来源:igfitidea点击:

getLastKnownLocation returns null

androidgoogle-mapslocation

提问by Aleksander Fimreite

I've read some questions about this, but I didn't quite find an answer that I needed.

我已经阅读了一些关于此的问题,但我没有完全找到我需要的答案。

So, the case is that I have my map set up, and I want to grab my current gps location. I have checked that my variables is not NULL but yet my result from:

所以,情况是我已经设置了地图,并且我想获取我当前的 GPS 位置。我已经检查过我的变量不是 NULL 但我的结果来自:

getLastKnownLocation(provider, false);

Gives me null though, so this is where I need help. I have added permissions for COARSE + FINE location. But I usually have all kinds of network data disabled for my phone, because I'm not very happy about unpredictable dataflow expenses in my phone bill. So I have only WiFi enabled and connected for this test.

虽然给了我null,所以这是我需要帮助的地方。我已经为 COARSE + FINE 位置添加了权限。但是我通常会为我的手机禁用各种网络数据,因为我对电话帐单中不可预测的数据流费用不太满意。所以我只启用并连接了 WiFi 以进行此测试。

Is there anything more I NEED to enable in order for this to be possible? I would think WiFi should be sufficient?

为了使这成为可能,我还需要启用什么吗?我认为WiFi应该足够了?

回答by TharakaNirmana

Use this method to get the last known location:

使用此方法获取最后一个已知位置:

LocationManager mLocationManager;
Location myLocation = getLastKnownLocation();

private Location getLastKnownLocation() {
    mLocationManager = (LocationManager)getApplicationContext().getSystemService(LOCATION_SERVICE);
    List<String> providers = mLocationManager.getProviders(true);
    Location bestLocation = null;
    for (String provider : providers) {
        Location l = mLocationManager.getLastKnownLocation(provider);
        if (l == null) {
            continue;
        }
        if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
            // Found best last known location: %s", l);
            bestLocation = l;
        }
    }
    return bestLocation;
}

回答by Binesh Kumar

you are mixing the new and the old location API's together when you shouldnt.

当您不应该将新旧位置 API 混合在一起时。

to get the last known location all your have to do is call

要获得最后一个已知位置,您只需致电

compile "com.google.android.gms:play-services-location:11.0.1"
mLocationClient.getLastLocation();

once the location service was connected.

一旦连接了定位服务。

read how to use the new location API

阅读如何使用新的位置 API

http://developer.android.com/training/location/retrieve-current.html#GetLocation

http://developer.android.com/training/location/retrieve-current.html#GetLocation

 private void getLastLocationNewMethod(){
    FusedLocationProviderClient mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    mFusedLocationClient.getLastLocation()
            .addOnSuccessListener(new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    // GPS location can be null if GPS is switched off
                    if (location != null) {
                        getAddress(location);
                    }
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.d("MapDemoActivity", "Error trying to get last GPS location");
                    e.printStackTrace();
                }
            });
}

回答by Sagar Maiyad

You are trying to get the cached location from the Network Provider. You have to wait for a few minutes till you get a valid fix. Since the Network Provider's cache is empty, you are obviously getting a null there..

您正在尝试从网络提供商处获取缓存位置。您必须等待几分钟才能获得有效修复。由于网络提供商的缓存是空的,你显然在那里得到了一个空值..

回答by Krupa Kakkad

Add this code

添加此代码

if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
     return;
}

beforethe function:

函数之前

locationManagerObject.requestLocationUpdates(LocationManager.GPS_PROVIDER, MINIMUM_TIME_BETWEEN_UPDATES, MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, new LocationListener())as well as the function: locationManagerObject.getLastKnownLocation(LocationManager.GPS_PROVIDER)

locationManagerObject.requestLocationUpdates(LocationManager.GPS_PROVIDER, MINIMUM_TIME_BETWEEN_UPDATES, MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, new LocationListener())以及功能: locationManagerObject.getLastKnownLocation(LocationManager.GPS_PROVIDER)

回答by Sumit Sinha

Try this it works good for me :-

试试这个它对我很有用:-

LocationManager mLocationManager;
Location myLocation = getLastKnownLocation();

        private Location getLastKnownLocation() {
            Location oldLoc;
            while (true){
                oldLoc = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                if (oldLoc == null){
                    continue;
                }
                else {
                    break;
                }
            }
            return oldLoc;
        }

You can use NETWORK_PROVIDER in place of GPS_PROVIDER for faster results..

您可以使用 NETWORK_PROVIDER 代替 GPS_PROVIDER 以获得更快的结果..

回答by Juned Khan Momin

I had this problem in Xamarin.Android.

我在 Xamarin.Android 中遇到了这个问题。

Location location = locationManager.GetLastKnownLocation(provider);was returning null value. I checked my code and got to know that I had just requested permission for ACCESS_COARSE_LOCATION. I added code to request permission for ACCESS_FINE_LOCATION and now it was not returning null. Here is my code:

Location location = locationManager.GetLastKnownLocation(provider);正在返回空值。我检查了我的代码并知道我刚刚请求了 ACCESS_COARSE_LOCATION 的许可。我添加了代码来请求 ACCESS_FINE_LOCATION 的权限,现在它没有返回 null。这是我的代码:

void AskPermissions()
{
    if (CheckSelfPermission(Manifest.Permission.AccessCoarseLocation) != (int)Permission.Granted ||
            CheckSelfPermission(Manifest.Permission.AccessFineLocation) != (int)Permission.Granted)
        RequestPermissions(new string[] { Manifest.Permission.AccessCoarseLocation, Manifest.Permission.AccessFineLocation }, 0);
    else
        GetLocation();
}

public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
    if (CheckSelfPermission(Manifest.Permission.AccessCoarseLocation) == (int)Permission.Granted &&
            CheckSelfPermission(Manifest.Permission.AccessFineLocation) == (int)Permission.Granted)
        GetLocation();
    else
        Log.Info(tag, "Permission not Granted: Please enter desired Location manually.");
}

void GetLocation()
{
    locationManager = (LocationManager)GetSystemService(LocationService);
    provider = locationManager.GetBestProvider(new Criteria(), false);
    Location location = locationManager.GetLastKnownLocation(provider);
    if (location != null)
        Log.Info(tag, "Location Lat: " + location.Latitude + " Lon: " + location.Longitude);
    else
        Log.Info(tag, "Location is null");
}

In case anyone coming from Xamarin.Android (C#) would find it useful. For Java or Android Studio the code would be similar withs some minor Syntax changes like GetLastKnownLocation()will be getLastKnownLocation()as method names in Java start with lowercase letters while in C# method names start with Uppercase letters.

以防万一来自 Xamarin.Android (C#) 的人会发现它很有用。对于Java或Android Studio中的代码将是类似withs一些小的语法更改,如GetLastKnownLocation()getLastKnownLocation()在Java方法的名称以小写字母开始,而在C#方法名以大写字母开头。

回答by P. J. Alzab

I liked this solution to update location:

我喜欢这个更新位置的解决方案:

Update location

更新位置

In resume, add the condition:

在简历中,添加条件:

Location myLocation = getLastKnownLocation();
if (myLocation == null) {
      locationManager.requestLocationUpdates(
      LocationManager.PASSIVE_PROVIDER,
      MIN_TIME_BW_UPDATES,
      MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
      Log.d("GPS", "GPS Enabled");
 }

And maybe is some basic, but check that GPS is ON.

也许是一些基本的,但检查 GPS 是否打开。

回答by Deepak Vajpayee

Replace ur line with

将您的行替换为

Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);