Android 如何确保每次询问时获得gps位置

Android 如何确保每次询问时获得gps位置,android,null,geolocation,location,android-gps,Android,Null,Geolocation,Location,Android Gps,在我的应用程序中,人们发布其他人可以看到的广告。他们被过滤使用之间的距离的创造者的annonce和家伙阅读它。 如果有人发布广告,我需要确定他的位置。如果有人在找广告,我需要确定他的位置,以便对广告进行分类 在我的代码中,我有一种获取位置的方法,但它有时返回null 这是小代码(我已经检查了权限等) 但是有时候,Location currentLocation=(Location)任务.getResult()返回null,即使任务已成功完成。我真的不知道为什么。 我想知道是否有一个可靠的方法,无

在我的应用程序中,人们发布其他人可以看到的广告。他们被过滤使用之间的距离的创造者的annonce和家伙阅读它。 如果有人发布广告,我需要确定他的位置。如果有人在找广告,我需要确定他的位置,以便对广告进行分类

在我的代码中,我有一种获取位置的方法,但它有时返回null

这是小代码(我已经检查了权限等)

但是有时候,
Location currentLocation=(Location)任务.getResult()返回null,即使任务已成功完成。我真的不知道为什么。
我想知道是否有一个可靠的方法,无论我问它的位置(它的位置是启用在电话上当然)。

谢谢你

那是因为你只要求得到最后一个位置。如果其他应用程序最近一直在使用gps,Te设备可以拥有它,但有时需要一段时间才能找到位置

您应该订阅位置更改,并至少等到您获得第一个位置。一种方法是仅在收到最后一个位置为空时订阅。在这种情况下,您应该执行
requestLocationUpdates
,并通过回调请求权限,以防您需要该位置(如果应用程序位于后台),并且如果您只需要一个位置,则可以在第一个位置到达后使用
removeLocationUpdates
停止该位置

看。或者你可以使用一个库,比如说,如果你觉得与可观察对象比回调更合适的话

 FusedLocationProviderClient mFusedLocationProviderClient;
    mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(context);

    try{
        if(mLocationPermissionsGranted){
            final Task location = mFusedLocationProviderClient.getLastLocation();
            location.addOnCompleteListener(new OnCompleteListener() {
                @Override
                public void onComplete(@NonNull Task task) {
                    if(task.isSuccessful()){
                        Log.d(TAG, "onComplete: found location!");

                        Location currentLocation = (Location) task.getResult();

                        if (currentLocation != null)
                        {
                            double Latit = currentLocation.getLatitude();
                            double Longit = currentLocation.getLongitude();

                            LatLng latLong = new LatLng(Latit, Longit);
                        //TODO do something with latlong
                        }
                    }else{
                        Log.d(TAG, "onComplete: current location is null");
                        Toast.makeText(context, "unable to get current location", Toast.LENGTH_SHORT).show();




                    }
                }
            });
        }
    }catch (SecurityException e){
        Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage() );
    }