【发布时间】:2021-11-28 04:33:05
【问题描述】:
我认为您可以使用 FusedLocationProviderClient 代替 LocationManager 来获取纬度、经度、日期和时间。这是我的代码
private FusedLocationProviderClient fusedLocationClient;
private Location lastKnownLocation;
private void getDeviceLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Task<Location> locationResult = fusedLocationClient.getLastLocation();
locationResult.addOnCompleteListener(this, new OnCompleteListener<Location>() {
@Override
public void onComplete(@NonNull Task<Location> task) {
if (task.isSuccessful()) {
// Set the map's camera position to the current location of the device.
lastKnownLocation = task.getResult();
if (lastKnownLocation != null) {
map.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(lastKnownLocation.getLatitude(),
lastKnownLocation.getLongitude()), DEFAULT_ZOOM));
long time = lastKnownLocation.getTime();
Date date = new Date(time);
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
String str=simpleDateFormat.format(date);
Toast.makeText(MapsActivity.this,"time: "+str,Toast.LENGTH_LONG).show();
}
}
}
});
}
这对我来说很好。如果有任何错误请提出建议,希望对您有所帮助。我没有包含 GPS 权限代码。如果你想要意味着我会在这里发布。
【问题讨论】:
标签: android locationmanager android-gps