首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么fusedLocationProviderClient.getLast位置总是返回null?

为什么fusedLocationProviderClient.getLast位置总是返回null?
EN

Stack Overflow用户
提问于 2021-12-20 14:34:14
回答 1查看 58关注 0票数 0

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

公共类MapsFragment扩展片段{

代码语言:javascript
运行
复制
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));
    }
}
EN

Stack Overflow用户

发布于 2021-12-20 14:38:26

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

票数 2
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70423403

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档