![](/img/trans.png)
[英]FusedLocationProviderClient.removeLocationUpdates always returns failure
[英]why fusedLocationProviderClient.getLast location always returns null?
我正在嘗試創建一個簡單的 android 應用程序,它必須在片段中顯示 map 和設備的最后一個已知位置。 I would like to use google API for the location, but when call the method fusedLocationProviderClient.getLastLocation the result is alway null and the position shown on the map is always latitude 0, longitude 0.
公共 class 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));
}
}
最后一個位置是設備上的一個緩存位置,因此獲取 null 意味着最近沒有使用該位置。 如果您首先打開谷歌地圖或使用您的 gps 位置的東西,讓它獲取您的位置,然后 go 回到您的應用程序中,您將獲得一個有效的位置
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.