为啥 fusedLocationProviderClient.getLast 位置总是返回 null?

Posted

技术标签:

【中文标题】为啥 fusedLocationProviderClient.getLast 位置总是返回 null?【英文标题】:why fusedLocationProviderClient.getLast location always returns null?为什么 fusedLocationProviderClient.getLast 位置总是返回 null? 【发布时间】:2022-01-22 03:56:03 【问题描述】:

我正在尝试创建一个简单的 android 应用程序,它必须在片段中显示地图以及设备的最后一个已知位置。我想使用 Google API 作为位置,但是每当我调用方法 fusedLocationProviderClient.getLastLocation 时,结果始终为空,并且地图上显示的位置始终为纬度 0,经度 0。

公共类 MapsFragment 扩展片段

FusedLocationProviderClient client;
double latitude, longitude;

private OnMapReadyCallback callback = new OnMapReadyCallback() 

    @Override
    public void onMapReady(GoogleMap googleMap) 

        //Check condition
        if (ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.ACCESS_FINE_LOCATION) ==
                PackageManager.PERMISSION_GRANTED &&
                ContextCompat.checkSelfPermission(getActivity(),
                        Manifest.permission.ACCESS_COARSE_LOCATION) ==
                        PackageManager.PERMISSION_GRANTED) 
            //When permission is granted, call method
            getCurrentLocation();
         else 
            //When permission is not granted, request permission
            requestPermissions(new String[]Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION, 100);
        


        //LatLng object creation
        LatLng latLng = new LatLng(latitude, longitude);

        //Set map coordinates using latLng object
        googleMap.addMarker(new MarkerOptions().position(latLng).title("Current Position"));
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    
;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater,
                         @Nullable ViewGroup container,
                         @Nullable Bundle savedInstanceState) 
    View v = inflater.inflate(R.layout.fragment_maps, container, false);
    return v;


@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) 
    super.onViewCreated(view, savedInstanceState);
    SupportMapFragment mapFragment =
            (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
    if (mapFragment != null) 
        mapFragment.getMapAsync(callback);
    



@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) 
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    //Check condition
    if (requestCode == 100 && (grantResults.length > 0) && (grantResults[0] + grantResults[1] ==
            PackageManager.PERMISSION_GRANTED)) 
        //When permission are granted, call method
        getCurrentLocation();
     else 
        Toast.makeText(getActivity(), "Permission denied", Toast.LENGTH_SHORT).show();
    


@SuppressLint("MissingPermission")
private void getCurrentLocation() 

    client = LocationServices.getFusedLocationProviderClient(getActivity());        

    //Initialize location manager, whose allow to get periodic updates of the location
    LocationManager locationManager = (LocationManager) getActivity()
            .getSystemService(Context.LOCATION_SERVICE);

    //Check condition, when GPS and NETWORK provider are enabled, WORK
    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
            || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) 
        //When location is enabled, get last location, THE PROBLEM IS THERE
        client.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() 
            @Override
            public void onComplete(@NonNull Task<Location> task) 
                Location location = task.getResult();
                //Check condition
                if (location != null) 
                    //When location result is not null, set latitude and longitude
                    latitude = location.getLatitude();
                    longitude = location.getLongitude();

                 else 
                    //When location result is not null, initialize location request
                    LocationRequest locationRequest = new LocationRequest()
                            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                            .setInterval(10000)
                            .setFastestInterval(1000)
                            .setNumUpdates(1);

                    //Initialize location callback
                    LocationCallback locationCallback = new LocationCallback() 
                        @Override
                        public void onLocationResult(@NonNull LocationResult locationResult) 
                            //Initialize location
                            Location location1 = locationResult.getLastLocation();
                            //Set latitude and longitude
                            latitude = location1.getLatitude();
                            longitude = location1.getLatitude();
                        
                    ;
                    //Request location updates
                    client.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
                
            
        );
     else 
        //When location service is not enabled, open location setting
        startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
                .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
    

【问题讨论】:

【参考方案1】:

最后一个位置是设备上的一个缓存位置,因此为空意味着最近没有使用该位置。如果您首先打开谷歌地图或使用您的 gps 位置的东西,让它获取您的位置,然后返回您的应用程序,您将获得一个有效的位置

【讨论】:

以上是关于为啥 fusedLocationProviderClient.getLast 位置总是返回 null?的主要内容,如果未能解决你的问题,请参考以下文章

为啥 DataGridView 上的 DoubleBuffered 属性默认为 false,为啥它受到保护?

为啥需要softmax函数?为啥不简单归一化?

为啥 g++ 需要 libstdc++.a?为啥不是默认值?

为啥或为啥不在 C++ 中使用 memset? [关闭]

为啥临时变量需要更改数组元素以及为啥需要在最后取消设置?

为啥 CAP 定理中的 RDBMS 分区不能容忍,为啥它可用?