Recentemente, ho creato una semplice applicazione per ottenere la posizione GPS e la visualizzazione sul telefono Android. All'inizio sono riuscito a ottenere la posizione dopo qualche tentativo, ma dopo aver reinstallato il file apk, getLastKnownLocation() restituisce sempre un valore null. ambientegetlastknownlocation restituisce sempre null dopo aver reinstallato il file apk tramite eclipse
sviluppo usato: - API 10 gingerbread 2.3.6 - fornitore di GPS viene usato
sotto è il codice ho applicato nel mio progetto Android:
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();
}
}
}
Qualcuno può suggerire una possibile soluzione risolvere il valore nullo restituito da getLastKnownLocation()? Qualsiasi aiuto sarà apprezzato. Grazie.
Grazie. Questo ha risolto il problema. – Student
È un grande codice. Molte grazie. –
Non è un gran bel codice ... mettere tutto il codice in un try/catch senza che ne abbia esplicitamente bisogno è una cattiva programmazione in linea di principio. Se vuoi davvero un bel pezzo di codice, prova questo: https://web.archive.org/web/20100429083435/http://marakana.com/forums/android/android_examples/42.html –