gpt4 book ai didi

java - 如何获取 Android 设备的经纬度?

转载 作者:行者123 更新时间:2023-12-01 19:17:35 26 4
gpt4 key购买 nike

所以我正在制作这个应用程序,它可以使用 JSoup 库查找您附近的餐馆,从食品配送应用程序中获取信息。唯一的问题是有时纬度和经度会变为空值。我的应用程序运行的情况: -开启GPS并等待至少1-2分钟; -打开谷歌地图,关闭它,然后返回到应用程序;

所以主要问题是:在启用位置并点击“查找餐馆”按钮后,我无法立即获取位置,启用位置后我需要等待 1-2 分钟,然后它才能工作。

    private TextView result;
private FusedLocationProviderClient client;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

requestPermission();
client = LocationServices.getFusedLocationProviderClient(this);

getBtn = findViewById(R.id.getRestaurants);
result = findViewById(R.id.restaurantsList);

getBtn.setOnClickListener(this);
}



private void requestPermission(){
ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION}, 1 );
}


public void onClick(View v) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
return;
}

client.getLastLocation().addOnSuccessListener(MainActivity.this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
result.setText("Getting location...");
if(location != null){
double latitude = getLat(location);
double longitude = getLng(location);

result.setText("Finding restaurants near you...");
getWebsite(latitude, longitude);
}else{
result.setText("Couldn't fetch location!");
}

}
});

最佳答案

这是在 Kotlin 中实现 FusedLocationProvider 的好方法(您可以适应 Java 或并行使用 Java 和 Kotlin):

private fun startLoc() {
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
try {
fusedLocationClient.lastLocation
.addOnSuccessListener { location: Location? ->
//showDialog(this@MapsActivity, TAG, "last know loc = ${location?.latitude} + ${location?.longitude}")
if (location != null){
lastKnowLoc = LatLng(location.latitude, location.longitude)
addMarkerToLocation(lastKnowLoc)
}
}
val locationRequest = LocationRequest()
locationRequest.interval = 10000
locationRequest.fastestInterval = 10000
locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY

locationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult?) {
locationResult ?: return
for (location in locationResult.locations){
//showDialog(this@MapsActivity, "locationResult", "location=${location.latitude};${location.longitude}")
addMarkerToLocation(LatLng(location.latitude, location.longitude))
val speed = location.speed
updateCamera(location.bearing)
}
}
}

fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null)

btnStartLoc.isEnabled = false
btnStopLoc.isEnabled = true
}catch (e:SecurityException){}

}

关于java - 如何获取 Android 设备的经纬度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59401709/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com