2012-03-26 26 views
14

Sto cercando di trovare la mia posizione corrente per un progetto Android. Quando l'applicazione viene caricata, la mia posizione corrente è sempre nullo. Ho impostato le autorizzazioni nel file manifest ecc. Quando trovo la posizione corrente, intendo utilizzare le coordinate per trovare le distanze in altre posizioni sulla mappa. Il mio snippet di codice è sotto. Perché ottengo sempre un valore nullo?La posizione corrente restituisce sempre null. Come posso risolvere questo?

locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);   
Criteria crit = new Criteria();  
towers = locMan.getBestProvider(crit, false); 
location = locMan.getLastKnownLocation(towers);  

if (location != null) {     
    System.out.println("Location is not null!"); 
    lat = (int) (location.getLatitude() *1E6); 
    longi = (int) (location.getLongitude() * 1E6); 
    GeoPoint ourLocation = new GeoPoint(lati, longi); 
    OverlayItem overlayItem = new OverlayItem(ourLocation, "1st String", 
                  "2nd String"); 
    CustomPinpoint custom = new CustomPinpoint(d, MainMap.this); 
    custom.insertPinpoint(overlayItem); 
    overlayList.add(custom); 
    overlayList.clear(); 
} else { 
    System.out.println("Location is null! " + towers); 
    Toast.makeText(MainMap.this, "Couldn't get provider",Toast.LENGTH_SHORT) 
                    .show(); 
} 
+0

Prova ad accedere a google maps direttamente non dall'app. Funziona - ti localizza? dopo aver individuato il tuo codice funziona come previsto?Esegui il test su dispositivo o emulatore? –

+0

Sto testando l'emulatore, sto usando il livello API 15. Non mi localizzerà, restituisce sempre null. Ho anche provato ad accedere all'applicazione google maps sull'emulatore, ma non riesco a trovare la posizione – devinefergal

+0

che stai usando modo scorretto segui questo https://stackoverflow.com/a/48033659/4997704 –

risposta

32

getLastKnownLocation() usa la posizione (s) in precedenza trovato da altre applicazioni. se nessuna applicazione lo ha fatto, allora getLastKnownLocation() restituirà null.

una cosa che puoi fare al tuo codice per avere una migliore possibilità di ottenere come ultima posizione conosciuta - iterare su tutti i provider abilitati, non solo il miglior provider. per esempio,

private Location getLastKnownLocation() { 
    List<String> providers = mLocationManager.getProviders(true); 
    Location bestLocation = null; 
    for (String provider : providers) { 
     Location l = mLocationManager.getLastKnownLocation(provider); 
     ALog.d("last known location, provider: %s, location: %s", provider, 
       l); 

     if (l == null) { 
      continue; 
     } 
     if (bestLocation == null 
       || l.getAccuracy() < bestLocation.getAccuracy()) { 
      ALog.d("found best last known location: %s", l); 
      bestLocation = l; 
     } 
    } 
    if (bestLocation == null) { 
     return null; 
    } 
    return bestLocation; 
} 

se la vostra applicazione non può fare senza avere una posizione, e se non c'è ultima posizione nota, avrete bisogno di ascoltare per gli aggiornamenti di posizione. si può dare un'occhiata a questa classe per un esempio,

https://github.com/farble1670/autobright/blob/master/src/org/jtb/autobright/EventService.java

vedere il metodo onStartCommand(), dove si controlla se il provider di rete è abilitata. in caso contrario, utilizza l'ultima posizione nota. se è abilitato, si registra per ricevere gli aggiornamenti di posizione.

+6

Perché 'if (bestLocation == null) {return null ; } return bestLocation; 'e non solo' return bestLocation; '? Vedi anche [qui] (http://stackoverflow.com/questions/2250597/find-current-location-latitude-and-longitude#comment25840492_2251680) –

+0

NPE sul registro se la posizione è nullo –

+1

Grazie amico. Mi salvi molto. – philip

0

Hai provato a invertire il codice? Ad esempio, se (posizione == null), stampare quella posizione è nullo, e altrimenti la posizione di stampa non è nullo. Ho avuto quel problema una volta prima e questo sembrava averlo risolto (non so perché). Prova questo.

Se ciò non funziona, forse l'API di google maps restituisce il valore null, nel qual caso è un problema con l'API GM o con il metodo di chiamata. Ognuno di questi potrebbe essere il problema.

Spero che questo aiuti,

-JXP

7

se u trovare posizione corrente dei dispositivi l'uso seguente metodo nella classe principale

public void find_Location(Context con) { 
    Log.d("Find Location", "in find_location"); 
    this.con = con; 
    String location_context = Context.LOCATION_SERVICE; 
    locationManager = (LocationManager) con.getSystemService(location_context); 
    List<String> providers = locationManager.getProviders(true); 
    for (String provider : providers) { 
     locationManager.requestLocationUpdates(provider, 1000, 0, 
      new LocationListener() { 

       public void onLocationChanged(Location location) {} 

       public void onProviderDisabled(String provider) {} 

       public void onProviderEnabled(String provider) {} 

       public void onStatusChanged(String provider, int status, 
         Bundle extras) {} 
      }); 
     Location location = locationManager.getLastKnownLocation(provider); 
     if (location != null) { 
      latitude = location.getLatitude(); 
      longitude = location.getLongitude(); 
      addr = ConvertPointToLocation(latitude, longitude); 
      String temp_c = SendToUrl(addr); 
     } 
    } 
} 

E Aggiungi metodo Autorizzazione utente nel file manifest

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> 
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> 
+1

Questo è bello – stepheaw

0

Prova questa questo non lo farà darti la posizione attuale nuda

class GetLastLocation extends TimerTask { 

    LocationManager mlocManager = (LocationManager) 
      getSystemService(Context.LOCATION_SERVICE); 
    LocationListener mlocListenerTmp = new CustomLocationListener(); 
    private final Handler mLocHandler; 

    public GetLastLocation(Handler mLocHandler) { 
     this.mLocHandler = mLocHandler; 
    } 

    @Override 
    public void run() { 
     timer.cancel(); 
     mlocManager.removeUpdates(mlocListenerTmp); 
     Location location = mlocManager 
       .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
     { 
      if (mlocListenerTmp != null) { 
       mlocManager.removeUpdates(mlocListenerTmp); 
      } 
      currentLocation = location; 
     } 
     if (location != null) { 
      String message = String.format(
       "Location \n Longitude: %1$s \n Latitude: %2$s", 
       location.getLongitude(), location.getLatitude()); 
      Log.d("loc", " :" + message); 
      Bundle b = new Bundle(); 
      { 
       b.putBoolean("locationRetrieved", true); 
       { 
        Message msg = Message.obtain(); 
        { 
         msg.setData(b); 
         mLocHandler.sendMessage(msg); 
        } 
       } 
      } 
     } else { 
      Log.d(
       "loc", 
       ":No GPS or network signal please fill the location manually!"); 
      location = mlocManager 
        .getLastKnownLocation(LocationManager.GPS_PROVIDER); 
      if (location != null) { 
       currentLocation = location; 
       Bundle b = new Bundle(); 
       { 
        b.putBoolean("locationRetrieved", true); 
        { 
         Message msg = Message.obtain(); 
         { 
          msg.setData(b); 
          mLocHandler.sendMessage(msg); 
         } 
        } 
       } 
      } else { 
       Bundle b = new Bundle(); 
       { 
        b.putBoolean("locationRetrieved", false); 
        { 
         Message msg = Message.obtain(); 
         { 
          msg.setData(b); 
          mLocHandler.sendMessage(msg); 
         } 
        } 
       } 
      } 
     } 
    } 
} 

chiamare in questo modo

timer.schedule(new GetLastLocation(mLocHandler), 3000); 

e la customLocationclass è la seguente

public class CustomLocationListener implements LocationListener { 

    @Override 
    public void onLocationChanged(Location loc) { 
     loc.getLatitude(); 
     loc.getLongitude(); 
     currentLocation = loc; 
     String Text = "My current location is: " + "Latitud = " 
      + loc.getLatitude() + "Longitud = " + loc.getLongitude(); 
     Log.d("loc", "onLocationChanged" + Text); 
    } 

    @Override 
    public void onProviderDisabled(String provider) {} 

    @Override 
    public void onProviderEnabled(String provider) {} 

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

Perché stai usando tutte le parentesi graffe extra ?? –

0

Se si sta cercando fuori in un dispositivo di marshmallow, provare ad abilitare luogo il permesso per la vostra applicazione manualmente.

Problemi correlati