如何适应Android设备的经度和纬度? [英] How can I cat latitude and longitude of Android device?

查看:82
本文介绍了如何适应Android设备的经度和纬度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So I'm making this app which finds restaurants near you, fetching information from a food-delivery app, using JSoup library. The only problem with it is that sometimes the latitude and the longitude are getting null value. Situations in which my application is working: -turning on GPS and the waiting at least 1-2 minutes; -opening google maps, closing it, and then returning to the application;

所以主要问题:启用该功能后,我无法立即获取位置并点击查找餐厅"按钮,启用位置后我需要等待1-2分钟,然后它才能正常工作.

So the main problem: I can't fetch the location right after I enable it and hit the 'Find restaurants' button, I need to wait 1-2 minutes after enabling location, then it's working.

    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!");
                }

            }
            });

推荐答案

您必须使用 requestLocationUpdates()您正在使用 getLastLocation(),并且当GPS在最后一个已知位置变为空后关闭并打开时,必须调用 requestLocationUpdates()您可以在下面的链接中找到更多信息

you must use requestLocationUpdates() you are using getLastLocation() and when the GPS is off and turned on after the last known location becomes null so you must call requestLocationUpdates() you can find more information in the below link

https://developer.android.com/training/location/receive-location-updates

这篇关于如何适应Android设备的经度和纬度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆