我想在Button按下获取Location对象。 我知道LocationListener回调,但它们只在特定时间或距离后执行。我想立即获得位置。有没有办法这样做。
答案 0 :(得分:5)
public class GPSHelper {
private Context context;
// flag for GPS Status
private boolean isGPSEnabled = false;
// flag for network status
private boolean isNetworkEnabled = false;
private LocationManager locationManager;
private Location location;
private double latitude;
private double longitude;
public GPSHelper(Context context) {
this.context = context;
locationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
} public void getMyLocation() {
List<String> providers = locationManager.getProviders(true);
Location l = null;
for (int i = 0; i < providers.size(); i++) {
l = locationManager.getLastKnownLocation(providers.get(i));
if (l != null)
break;
}
if (l != null) {
latitude = l.getLatitude();
longitude = l.getLongitude();
}
}
public boolean isGPSenabled() {
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
return (isGPSEnabled || isNetworkEnabled);
}
/**
* Function to get latitude
*/
public double getLatitude() {
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude() {
return longitude;
}
答案 1 :(得分:2)
欢迎您致电getLastKnownLocation()
上的LocationManager
来检索您所请求的位置提供商的最后一个已知位置。但是:
null
因此,您的代码需要能够应对这两种情况。
答案 2 :(得分:0)
使用LocationManager
类:
locationManager = (LocationManager)this.getSystemService(LOCATION_SERVICE);
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude=location.getLatitude();
longitude=location.getLongitude();
Log.d("old","lat : "+latitude);
Log.d("old","long : "+longitude);
this.onLocationChanged(location);
}
答案 3 :(得分:0)
请尝试以下操作: https://github.com/delight-im/Android-SimpleLocation
如果启用了您的位置信息,则只需3行代码:
usersSelected: boolean = false;
myMethod(): void {
this.usersSelected = false;
}
答案 4 :(得分:0)
您可以使用FusedLocationProviderClient获取最新的已知位置
有非常简单的步骤来获取当前的纬度,经度,海拔和方位
(i) Kotlin代码
private lateinit var fusedLocationClient: FusedLocationProviderClient
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
fusedLocationClient.lastLocation
.addOnSuccessListener { location: Location? ->
Log.d(TAG, "latitude:" + location?.latitude)
Log.d(TAG, "longitude:" + location?.longitude)
Log.d(TAG, "altitude:" + location?.altitude)
Log.d(TAG, "bearing:" + location?.bearing)
}
(ii)JAVA代码
private FusedLocationProviderClient fusedLocationClient;
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
fusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null) {
Log.d(TAG,location.getLatitude)
Log.d(TAG,location.getLongitude)
}
}
});
就是这样。运行您的代码,您可以在Logcat中检查您的当前位置。不要忘记从模拟器或Android手机接受位置权限。
使用FusedLocationProviderClient无法获得适当的高度和方位。
快乐编码:)