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

标签 java android google-play-services android-location getlocation

所以我正在制作这个应用程序,它可以使用 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/

相关文章:

java - 错误 : Could not find or load main class

android - 使用 SkiaSharp 在 Xamarin 中加载 SVG 文件

java - 无法从抽屉导航中的 Fragment/FragmentActivity 打开 FragmentActivity

android - 更新到最新版本 (3.1) 后缺少 google-play-services_lib.jar

android - 更改标题后,Google Play Top Charts 应用不再排名?

java - 将 java.util.Properties 与 Hibernate 保持一致?

java - 可以控制 Java 中对象的身份吗?如果可以,如何控制?

java - maven-clean-plugin 没有删除所有给定的目录

android - 如何更改导航 View 项目的文本大小?

android - 无法在 Debug模式下登录 Google Play 服务