2013-04-14 8 views
21

Niedawno stworzyłem prostą aplikację, aby uzyskać lokalizację GPS i wyświetlić na telefonie z Androidem. Na początku mogę uzyskać lokalizację po kilku próbach, ale po ponownym zainstalowaniu pliku apk funkcja getLastKnownLocation() zawsze zwraca wartość pustą. Środowiskogetlastknownlocation zawsze zwraca wartość null po ponownym zainstalowaniu pliku APK za pośrednictwem eclipse

Development używane: - API 10 Gingerbread 2.3.6 - dostawca GPS służy

poniżej jest kod zastosowałem w moim android projektu:

 public class MyActivity extends MapActivity{ 
protected void onCreate(Bundle savedInstanceState) { 


    mapView = (MapView)findViewById(R.id.myTripMap); 
    mapController = mapView.getController(); 
    mapView.setSatellite(false); 
    mapView.setStreetView(true); 
    mapView.displayZoomControls(false); 
    mapView.setBuiltInZoomControls(true);// 
    mapView.setClickable(true); 
    mapController.setZoom(14);  


    Criteria criteria = new Criteria(); 
    criteria.setAccuracy(Criteria.ACCURACY_FINE); 
    criteria.setAltitudeRequired(false); 
    criteria.setBearingRequired(false); 
    criteria.setCostAllowed(true); 
    criteria.setPowerRequirement(Criteria.POWER_LOW); 
    provider = locationManager.getBestProvider(criteria, true); 
    location = locationManager.getLastKnownLocation(provider); 

    updateMyCurrentLoc(location); 

    locationManager.requestLocationUpdates(provider, 2, 1,locationListener); 



} 


      private final LocationListener locationListener = new LocationListener() { 
     public void onLocationChanged(Location location) { 
      updateMyCurrentLoc(location); 
     } 

     public void onProviderDisabled(String provider){ 
      updateMyCurrentLoc(null); 
     } 

     public void onProviderEnabled(String provider){ } 
     public void onStatusChanged(String provider, int status, 
            Bundle extras){ } 
     }; 


     private void updateMyCurrentLoc(Location location) { 



      if (location != null) { 

      // other codes to get the address and display 
      Toast.makeText(getBaseContext(), "provider used : "+provider).show(); //testing purpose 
      } 
      else { 
       str = "No location found"; 
       Toast.makeText(getBaseContext(), str, Toast.LENGTH_SHORT).show(); 
      } 

     } 
    } 

Może ktoś sugerują możliwe rozwiązanie rozwiązać wartość pustą zwróconą przez getLastKnownLocation()? Każda pomoc zostanie doceniona. Dzięki.

Odpowiedz

42

getLastKnownLocation() ta zwraca ostatnią znaną lokalizację ... po ponownym zainstalowaniu aplikacji nie będą miały żadnego ostatnią znaną lokalizację ... więc będzie skutkować NPE ... zamiast skorzystać z poniższego kodu

public Location getLocation() { 
    try { 
     locationManager = (LocationManager) mContext 
       .getSystemService(LOCATION_SERVICE); 

     // getting GPS status 
     isGPSEnabled = locationManager 
       .isProviderEnabled(LocationManager.GPS_PROVIDER); 

     // getting network status 
     isNetworkEnabled = locationManager 
       .isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

     if (!isGPSEnabled && !isNetworkEnabled) { 
      // no network provider is enabled 
     } else { 
      this.canGetLocation = true; 
      if (isNetworkEnabled) { 
       locationManager.requestLocationUpdates(
         LocationManager.NETWORK_PROVIDER, 
         MIN_TIME_BW_UPDATES, 
         MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
       Log.d("Network", "Network Enabled"); 
       if (locationManager != null) { 
        location = locationManager 
          .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
        if (location != null) { 
         latitude = location.getLatitude(); 
         longitude = location.getLongitude(); 
        } 
       } 
      } 
      // if GPS Enabled get lat/long using GPS Services 
      if (isGPSEnabled) { 
       if (location == null) { 
        locationManager.requestLocationUpdates(
          LocationManager.GPS_PROVIDER, 
          MIN_TIME_BW_UPDATES, 
          MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
        Log.d("GPS", "GPS Enabled"); 
        if (locationManager != null) { 
         location = locationManager 
           .getLastKnownLocation(LocationManager.GPS_PROVIDER); 
         if (location != null) { 
          latitude = location.getLatitude(); 
          longitude = location.getLongitude(); 
         } 
        } 
       } 
      } 
     } 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

    return location; 
} 

on pracował dla mnie ... powinien pracować dla Ciebie ...

+0

Dzięki. To rozwiązało problem. – Student

+0

To świetny kod. Wielkie dzięki. –

+15

To nie jest świetny kod. Umieszczenie całego kodu wewnątrz try/catch bez żadnego z nich jawnie potrzebującego, to z zasady złe programowanie. Jeśli naprawdę potrzebujesz świetnego kodu, spróbuj tego: https://web.archive.org/web/20100429083435/http://marakana.com/forums/android/android_examples/42.html –

1

po prostu trzeba dodać jeszcze jedną linię w kodzie

if (locationManager != null) { 
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); 
    location = locationManager 
      .getLastKnownLocation(LocationManager.GPS_PROVIDER); 

    if (location != null) { 
     latitude = location.getLatitude(); 
     longitude = location.getLongitude(); 

    } else { 
     Toast.makeText(
       mContext, 
       "Location Null", Toast.LENGTH_SHORT).show(); 
    } 
} 
+0

co jeśli lokalizacja == null?Jak uzyskać dokładną lokalizację –

+0

czekać, co z tobą nie tak, nie wiem, co dokładnie próbujesz odpowiedzieć. Tutaj jest pytanie, czy ktoś powie mu rozwiązanie, jak pozbyć się tego obiektu zerowego zwracanego przez metodę getLastKnownLocation (PROVIDER). Nie pokazywać wiadomości z toastem, bez sugestii co dalej robić. – Khay

0

Spróbuj następujący kod

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

    String locationProvider = LocationManager.NETWORK_PROVIDER; 
    Location lastlocation = locationManager.getLastKnownLocation(locationProvider); 

    String CurLat = String.valueOf(lastlocation.getLatitude()); 
    String Curlongi= String.valueOf(lastlocation.getLongitude()); 
+1

Nie odpowiada na problem. –

-1

Mam ten sam problem po ponownym zainstalowaniu za pomocą eclipse. Rozwiązałem problem z ustawieniami Androida/bezpieczeństwa/aplikacji i potwierdziłem uprawnienia lokalizacji do aplikacji.

+2

To nie jest sposób, w jaki należy poprosić użytkownika o przyznanie tych uprawnień w środowisku wykonawczym. [Aby uzyskać więcej informacji, sprawdź to] (https://developer.android.com/guide/topics/security/permissions.html#normal-dangerous) – kId

1

To rozwiązanie jest moim małym usprawnieniem dla kodu @Karan Mer.

public Location getLocation() { 
    int MIN_TIME_BW_UPDATES = 10000; 
    int MIN_DISTANCE_CHANGE_FOR_UPDATES = 10000; 
    try { 
     locationManager = (LocationManager) getApplicationContext() 
       .getSystemService(LOCATION_SERVICE); 

     boolean isGPSEnabled = locationManager 
       .isProviderEnabled(LocationManager.GPS_PROVIDER); 

     boolean isPassiveEnabled = locationManager 
       .isProviderEnabled(LocationManager.PASSIVE_PROVIDER); 

     boolean isNetworkEnabled = locationManager 
       .isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

     if (isGPSEnabled || isNetworkEnabled || isPassiveEnabled) { 

      this.canGetLocation = true; 
      // if GPS Enabled get lat/long using GPS Services 
      if (isGPSEnabled && location == null) { 
        locationManager.requestLocationUpdates(
          LocationManager.GPS_PROVIDER, 
          MIN_TIME_BW_UPDATES, 
          MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
        Log.d("GPS", "GPS Enabled"); 
        if (locationManager != null) { 
         location = locationManager 
           .getLastKnownLocation(LocationManager.GPS_PROVIDER); 
        } 
      } 
      if (isPassiveEnabled && location == null) { 
       locationManager.requestLocationUpdates(
         LocationManager.PASSIVE_PROVIDER, 
         MIN_TIME_BW_UPDATES, 
         MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
       Log.d("Network", "Network Enabled"); 
       if (locationManager != null) { 
        location = locationManager 
          .getLastKnownLocation(LocationManager.PASSIVE_PROVIDER); 
       } 
      } 

      if (isNetworkEnabled && location == null) { 
       locationManager.requestLocationUpdates(
         LocationManager.NETWORK_PROVIDER, 
         MIN_TIME_BW_UPDATES, 
         MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
       Log.d("Network", "Network Enabled"); 
       if (locationManager != null) { 
        location = locationManager 
          .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
       } 
      } 

     }else{ 
      return null; 
     } 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

Ciesz

Powiązane problemy