有 Java 编程相关的问题?

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

java位置状态与Android Studio不一致

我正在尝试获取用户的当前位置,并在地图上显示一个标记。这是我的密码

public class MapsActivity extends AppCompatActivity implements LocationListener, OnMapReadyCallback {

    private GoogleMap mMap;
    LocationManager locationManager;
    String provider;
    Location mLocation;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);


        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        provider = locationManager.getBestProvider(new Criteria(), false);
        if (ActivityCompat.checkSelfPermission(this, 安卓.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 安卓.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        mLocation=locationManager.getLastKnownLocation(provider);



        if (mLocation != null) {
            Log.i("Location Status: ", "Location Found");
        } else if (mLocation == null) {
            Log.i("Location Status: ", "Location Not Found");
        }
    }



    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        if(mLocation!=null) {
            try {
                Double lat = mLocation.getLatitude();
                Double lng = mLocation.getLongitude();

                mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).title("My Location"));
                mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 12));
            } catch (Exception ex) {
                Log.e("Location Error:","Exception was "+ex);
            }
        }

    }

    @Override
    protected void onResume() {

        super.onResume();
        if (ActivityCompat.checkSelfPermission(this, 安卓.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 安卓.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        locationManager.requestLocationUpdates(provider, 400, 1, this);

    }

    @Override
    public void onLocationChanged(Location location) {


        mMap.addMarker(new MarkerOptions().position(new LatLng(location.getLatitude(), location.getLongitude())).title("My Location"));
        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 12));


    }

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

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {
        Toast.makeText(getApplicationContext(),"Please enable your location",Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onPause() {
        super.onPause();
        locationManager.removeUpdates(this);
    }
}

现在,问题是在我没有得到任何位置的大多数情况下,地图显示时没有任何标记,并且在日志“位置状态:未找到位置”中,如果位置为空,则设置为显示。 我试图重建并再次运行。现在在一台设备上检测到该位置,但在其他设备上显示相同的输出。我希望每次都能这样做,但这很奇怪,因为相同的代码在同一台设备上以相同的设置在不同的时间显示两种不同的行为。 在设备上启用了P.S.位置。 任何形式的帮助或提示都将不胜感激。谢谢


共 (1) 个答案

  1. # 1 楼答案

    试试我编写的代码

    • 有时GPS无法定位您的位置,这就是为什么您在null对象中获得mLocation
    • 所以我的建议是在网络提供商的基础上获得location

    这是我的代码

    public class MapsActivity extends FragmentActivity implements LocationListener, OnMapReadyCallback {
    
        private GoogleMap mMap;
        LocationManager locationManager;
        Location mLocation;
        // The minimum distance to change Updates in meters
        private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 10 meters
        // The minimum time between updates in milliseconds
        private static final long MIN_TIME_BW_UPDATES = 1000 * 60; // 1 minute
    
        boolean isGPSEnabled = false;
    
        // flag for network status
        boolean isNetworkEnabled = false;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_maps);
            // Obtain the SupportMapFragment and get notified when the map is ready to be used.
            SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map);
            mapFragment.getMapAsync(this);
    
    
            locationManager = (LocationManager) this
                    .getSystemService(LOCATION_SERVICE);
            locationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER,
                    MIN_TIME_BW_UPDATES,
                    MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
    
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    
            if (isGPSEnabled) {
                mLocation = locationManager
                        .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                if (mLocation == null) {
                    mLocation = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                }
            }
    
            if (locationManager != null) {
                if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    return;
                }
                if (mLocation != null) {
                    Log.e("Location Status: ", "Location Found");
                } else {
                    Log.e("Location Status: ", "Location Not Found");
                }
            }
        }
    
        @Override
        public void onMapReady(GoogleMap googleMap) {
            mMap = googleMap;
    
            /*// Add a marker in Sydney and move the camera
            LatLng sydney = new LatLng(-34, 151);
            mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
            mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));*/
    
            if (mLocation != null) {
                try {
                    Double lat = mLocation.getLatitude();
                    Double lng = mLocation.getLongitude();
    
                    mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).title("My Location"));
                    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 12.5f));
                } catch (Exception ex) {
                    Log.e("Location Error:", "Exception was " + ex);
                }
            }
        }
    
        @Override
        public void onLocationChanged(Location location) {
    
        }
    
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
    
        }
    
        @Override
        public void onProviderEnabled(String provider) {
            Toast.makeText(getApplicationContext(), "enable your location", Toast.LENGTH_LONG).show();
        }
    
        @Override
        public void onProviderDisabled(String provider) {
            Toast.makeText(getApplicationContext(), "Please enable your location", Toast.LENGTH_LONG).show();
        }
    
        @Override
        protected void onPause() {
            super.onPause();
            if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            locationManager.removeUpdates(this);
        }
    }