为什么getLastLocation返回null?

3

我已经尝试了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) {
    }
}

权限方面怎么样?已经在清单文件中添加了所需的权限(并在API23及以上版本上运行时请求)了吗? - Opiatefuchs
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
- Karo Hovhannisyan
运行时权限检查?您是在开发API =>23吗? - Opiatefuchs
在Karo提到的权限之上,记得打开你的GPS或其他定位服务吗? - Maytham Fahmi
请参见此处:http://developer.android.com/training/permissions/requesting.html - Opiatefuchs
显示剩余4条评论
3个回答

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

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级别>= 23

在下一次编辑中提供一些来自您的运行日志,以获得更多帮助。

编辑 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);
        }
    }

请求位置权限(); ? - Karo Hovhannisyan

0

getLastKnownLocation 如果没有缓存的上一次已知位置,将返回 null。与人们所想的不同,操作系统并不保证将其收到的最后位置存储在内存中,根据我的经验,这种情况因设备而异,因此您应始终检查 null 并相应处理。

因此,要实际回答您的问题,如果上一次已知位置为 null,则需要获取或等待当前位置。

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


getLastLocation() 方法从哪里获取位置坐标? - ThinkAndCode

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接