有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java位置在Android中显示为空

我在onCreate()onResume()方法中调用了这个方法

基本上,我正在使用它,这样我可以得到我当前位置的城市名称,并将其设置为字符串,以便以后使用。 为了看看它是否有效,我把它设置为我的欢迎文本

方法是:

    private void getLocation() {

        if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

            fusedLocationProviderClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {

                @Override
                public void onComplete(@NonNull Task<Location> task) {

                    Location location = task.getResult();
                    if (location != null) {

                        try {
                            Geocoder geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
                            List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);

                            cityName = addresses.get(0).getLocality(); // sets the address here
                            Welcome.setText(cityName);

                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    } else {
                        Toast.makeText(MainActivity.this, "Location null error", Toast.LENGTH_SHORT).show();
                    }
                }
            });

        } else {
            ActivityCompat.requestPermissions(MainActivity.this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION},44);
        }
    }

问题是,当我使用安卓 studio模拟器时,它在大多数情况下都能正常工作

但当我在手机上运行应用程序时,我会得到我设置的“位置空错误”吐司。 表示位置为空。即使在“设备设置”中启用了“位置”

我想不出是什么问题


共 (1) 个答案

  1. # 1 楼答案

    在您的情况下,您希望在locationupdates方法中使用地理编码器。一旦位置不为空,使用该位置查找您的地址,然后停止更新

    为此,您需要使用requestLocationUpdates,因为如果另一个应用程序在一定时间内没有请求位置,lastKnownlocation可能为null

    看看这个问题中的my answer。它将帮助您通过使用位置更新获取位置