无法从 Android Studio 上的位置服务获取坐标

时间:2021-04-14 04:12:16

标签: java android android-studio geolocation locationmanager

我是 Android Studio 的新手,正在尝试使用位置服务检索 Android 设备的坐标。

我在清单中启用了所有相关权限(粗略和精细位置,以及互联网)。

在我的 MainActivity.java 中,我有以下内容。但是,当我在 Android Studio 中运行它时,对于 Activity 中的 3 个测试用例,TextView ShowLocation 总是变成“其他”,这意味着它进入了第三个位置为空的情况(未检测到位置?)但已正确授予权限。

我在这里做错了什么?是不是因为我无法在 Android Studio 中测试定位服务?如何使用 Android Studio 在 Android 应用程序中测试和获取坐标值?

MainActivity.java

的一个片段
     locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
                        != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

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

                Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

                if (loc != null) {
                    latitude = String.valueOf(loc.getLatitude());
                    showLocation.setText("Latitude" + latitude);
                }

                else {

                    if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
                            != PackageManager.PERMISSION_GRANTED) {
                        showLocation.setText("No GPS Permission granted");
                   
                    } else
                        showLocation.setText("Something else");
                }

0 个答案:

没有答案
相关问题