启动Android应用后,GPS始终处于开启状态

时间:2016-03-11 10:08:28

标签: android gps

在我正在处理的应用中,我在活动的onCreate()方法中获取设备的GPS坐标。但是,即使在启动应用程序后,我也会看到位置服务图标一直闪烁在设备的通知栏中,这是预期的,还是应该在获取设备位置后消失?

这是我目前的代码:

if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_DENIED)
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        1);
            Criteria criteria = new Criteria();
            LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
            lm.requestLocationUpdates(lm.getBestProvider(criteria, true), 2000, 0, new android.location.LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    double latitude = location.getLatitude();
                    double longitude = location.getLongitude();
                }

                @Override
                public void onStatusChanged(String provider, int status, Bundle extras) {

                }

                @Override
                public void onProviderEnabled(String provider) {

                }

                @Override
                public void onProviderDisabled(String provider) {

                }
            });
            // Get latitude and longitude
            Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            longitude = location.getLongitude();
            latitude = location.getLatitude();

1 个答案:

答案 0 :(得分:1)

您永远不会告诉LocationManager停止提供位置更新。为此,请使用正确的侦听器作为参数调用LocationManager.removeUpdates()

或者,您可以使用LocationManager.requestSingleUpdate(...)自动停止在第一个位置后提供更新。