在 android 4.0 中获取位置到 android studio 中的问题

problem in getting location in android 4.0 to up in android studio

我想在服务中获取用户的纬度和经度,我在 android 4.4 下试过,所有的东西都很好,但在 android 4.4 到更高版本我无法获取用户位置 我已经拥有所有权限并且位置已启用。

最后:如果无论如何是为了在服务中获取位置,没有打开地图请告诉我

这是我的代码:

private static final int REQUEST_LOCATION = 1;
LocationManager locationManager;
 double lattitude, longitude;





     locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            buildAlertMessageNoGps();

        } else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {




            if (ActivityCompat.checkSelfPermission(MyService.this, Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission
                    (MyService.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

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

            } else {
                Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

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

                Location location2 = locationManager.getLastKnownLocation(LocationManager. PASSIVE_PROVIDER);

                if (location != null) {
                    double latti = location.getLatitude();
                    double longi = location.getLongitude();
                    lattitude = latti;
                    longitude =longi;



                } else  if (location1 != null) {
                    double latti = location1.getLatitude();
                    double longi = location1.getLongitude();
                    lattitude = latti;
                    longitude =longi;



                } else  if (location2 != null) {
                    double latti = location2.getLatitude();
                    double longi = location2.getLongitude();
                    lattitude = latti;
                    longitude =longi;


                }else{

                    Log.d("Location", "Cant Get Location ");

                }
            }








        //}
    }

您正在尝试获取最后的已知位置。但是您确定该设备具有最后已知的位置吗?我想你必须请求位置。

最后已知位置是设备上次获取纬度和经度的位置。

For testing before calling your app first open internet goto map and then off the internet and open your app then you will get lastKnown location

所以最后知道的位置取决于以前的位置。如果设备没有以前的位置,您将不会获得任何 lastKnown 位置。所以 location 将为空。

所以你必须请求位置。 locationmanager.requestLocationUpdates() 有关详细信息,您可以在 visit 此处查看。