为什么getLastLocation返回null?

时间:2016-03-15 08:33:41

标签: android maps

我试图在3天内解决这个问题。我已经忘记了调试,无法看到我的错误。 我正在尝试构建一个请求当前位置的应用程序。

我的getLastLocation返回null,任何人都可以指出我在哪里做错了吗?

这是我的代码

public class MapActivityFragment extends FragmentActivity implements 
        LocationListener,
        OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        GoogleMap.OnMarkerDragListener,
        GoogleMap.OnMapLongClickListener, View.OnClickListener {

    //Our Map
    private GoogleMap mMap;

    //To store longitude and latitude from map
    private double longitude;
    private double latitude;

    //Google ApiClient
    private GoogleApiClient googleApiClient;
    private ImageButton buttonCurrent;
    private TextView tv;
    private String myLocation;

    @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);

        tv = (TextView) findViewById(R.id.textViewTv);

        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        //Initializing googleapi client
        googleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

        buttonCurrent = (ImageButton) findViewById(R.id.buttonCurrent);
        buttonCurrent.setOnClickListener(this);

        //Initializing views and adding onclick listeners
    }

    @Override
    protected void onStart() {
        googleApiClient.connect();
        // Log.d("Tag Name", "GOOGLE  : : :  " + googleApiClient);
        super.onStart();
    }

    @Override
    protected void onResume() {
        googleApiClient.connect();
        super.onResume();
    }

    //Getting current location
    private void getCurrentLocation() {
        //mMap.clear();
        //Creating a location object
        Log.d("Tag Name", "GOOGLE  : : :  " + googleApiClient);
        Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
        Log.d("Tag Name", "asdsa " + location);
        Toast.makeText(MapActivityFragment.this, "googleApiclient:" + googleApiClient, Toast.LENGTH_LONG).show();
        Toast.makeText(MapActivityFragment.this, "location:" + location, Toast.LENGTH_LONG).show();

        mMap.clear();

        if (location != null) {
            Log.d("Tag Name", "2222");
            //Getting longitude and latitude
            longitude = location.getLongitude();
            latitude = location.getLatitude();
            tv.setText("longitude: " + longitude + " " + "latitude: " + latitude);

            //Toast.makeText(this, "long ; " + longitude, Toast.LENGTH_LONG).show();
            Log.d("Tag Name", "Log Message");

            //moving the map to location
            moveMap();
        }
    }

    //Function to move the map
    private void moveMap() {

        //String to display current latitude and longitude
        String msg = latitude + " , " + longitude;
        //Creating a LatLng Object to store Coordinates
        LatLng latLng = new LatLng(latitude, longitude);
        //Adding marker to map
        mMap.addMarker(new MarkerOptions()
                .position(latLng) //setting position
                .draggable(true) //Making the marker draggable
                .title("Current Location")); //Adding a title
        //Moving the camera
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        //Animating the camera
        //mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
        //Displaying current coordinates in toast
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        LatLng latLng = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(latLng).draggable(true));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.setOnMarkerDragListener(this);
        mMap.setOnMapLongClickListener(this);
    }

    @Override
    public void onConnected(Bundle bundle) {
        Log.i("TAG", "Location services connected.");
        getCurrentLocation();
    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.i("TAG", "Location services suspended. Please reconnect.");
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
    }

    @Override
    public void onMapLongClick(LatLng latLng) {
        mMap.clear();
        mMap.addMarker(new MarkerOptions()
                .position(latLng)
                .draggable(true));
    }

    @Override
    public void onMarkerDragStart(Marker marker) {
    }

    @Override
    public void onMarkerDrag(Marker marker) {
    }

    @Override
    public void onMarkerDragEnd(Marker marker) {
        latitude = marker.getPosition().latitude;
        longitude = marker.getPosition().longitude;
        moveMap();
    }

    @Override
    public void onClick(View v) {

        if (v == buttonCurrent) {
            mMap.setMyLocationEnabled(true);
            getCurrentLocation();
            //moveMap();
            mMap.addMarker(new MarkerOptions()
                    .position(new LatLng(40, 40)).title("Hello World"));
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        location.getLatitude();
        location.getLongitude();
        tv.setText("Latitude = " + location.getLatitude() + " 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) {
    }
}

3 个答案:

答案 0 :(得分:0)

试试这个..

List<String> providers = mLocationManager.getProviders(true);
android.location.Location bestLocation = null;
for (String provider : providers) {
    android.location.Location l = mLocationManager.getLastKnownLocation(provider);
    if (l == null) {
        continue;
    }
    if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
        // Found best last known location: %s", l);
        bestLocation = l;
    }
}
//bestlocation is required location

答案 1 :(得分:0)

如果没有缓存的最后一个已知位置,

getLastKnownLocation将返回null。与人们认为操作系统不保证存储在内存中的最后位置不同,根据我的经验,这会随设备的不同而变化,因此您应该始终检查空值并进行相应处理。

因此,要真正回答您的问题,如果最后一个已知位置为空,您需要等待当前位置。

http://developer.android.com/training/location/receive-location-updates.html

答案 2 :(得分:0)

这个对我有用,谷歌提供了一些变化。

@Override
public void onConnected(Bundle dataBundle) {
    // Display the connection status
    if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        requestLocationPermission();
        return;
    }
    Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if (location != null) {
        Toast.makeText(getActivity(), "GPS location was found!", Toast.LENGTH_SHORT).show();
        }
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 17);
        mMap.animateCamera(cameraUpdate);
        startLocationUpdates();
}

权限模型代码适用于API级别&gt; = 23

在下次编辑中提及您的RUN中的一些日志以获取更多帮助。

EDIT requestLocationPermission()要求用户允许使用该权限启用。

        protected void requestLocationPermission() {
        Log.i(TAG, "LOCATION permission has NOT been granted. Requesting permission.");

        if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                Manifest.permission.ACCESS_FINE_LOCATION) || ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                Manifest.permission.ACCESS_COARSE_LOCATION)) {
            // Provide an additional rationale to the user if the permission was not granted
            // and the user would benefit from additional context for the use of the permission.
            // For example if the user has previously denied the permission.
            Log.i(TAG,
                    "Displaying location permission rationale to provide additional context.");
// some snackbar thingy
        } else {
            // Camera permission has not been granted yet. Request it directly.
            ActivityCompat.requestPermissions(getActivity(), PERMISSIONS_LOCATION,
                    REQUEST_LOCATION);
        }
    }