Getting null from 'getLastKnownLocation' on SDK

前端 未结 6 1340
星月不相逢
星月不相逢 2020-12-01 19:52

I have a problem related to the Location API.

I tried the following code:

LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SER         


        
相关标签:
6条回答
  • 2020-12-01 20:35

    If you're running the code in the emulator, any calls to get the GPS location will return null until you explicitly update the location (via Eclipse or ADB).

    0 讨论(0)
  • 2020-12-01 20:35

    Have you set the permissions in your AndroidManifest.xml? You need these permissions in order to access the user's location with an application:

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
    
    0 讨论(0)
  • 2020-12-01 20:43

    Here's something you can use:

    LocationManager lm = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String bestProvider = lm.getBestProvider(criteria, false);
    Location loc = lm.getLastKnownLocation(bestProvider);
    
    last_lat = loc.getLatitude();
    last_lng = loc.getLongitude();
    
    0 讨论(0)
  • 2020-12-01 20:47

    Along with the permissions in your AndroidManifest.xml file, have you registered a location listener?

    LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    Location loc = getLastKnownLocation(LocationManager.GPS_PROVIDER);
    lm.requestLocationUpdates(LocationManager.GPS, 100, 1, locationListener); 
    

    Then have a method, in this case locationListener, to complete your task

    private final LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
        latitude = location.getLatitude();
        longitude = location.getLongitude();
    }
    
    0 讨论(0)
  • 2020-12-01 20:51

    You need the instance Of LocationManager like this:

    First Instance:

       LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    

    Wrong:

    Location loc = getLastKnownLocation(LocationManager.GPS_PROVIDER);
    

    Correct:

    Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    
    0 讨论(0)
  • 2020-12-01 20:57

    I had the same problem as you, I always receive a null Location object, But finally it was solved in an easy way. You must have a valid GPS location, so, if the GPS is not enabled and you dont't have enough signal, the Location object will be ALWAYS null.

    0 讨论(0)
提交回复
热议问题