Gần đây, tôi đã tạo một ứng dụng đơn giản để có được vị trí gps và hiển thị trên điện thoại Android. Lúc đầu tôi có thể nhận được vị trí sau khi thử một vài lần, nhưng sau khi tôi cài đặt lại tập tin apk, getLastKnownLocation() luôn trả về một giá trị null. môi trườnggetlastknownlocation luôn trả về null sau khi tôi cài đặt lại tập tin apk qua eclipse
Phát triển sử dụng: - API 10 gingerbread 2.3.6 - nhà cung cấp GPS được sử dụng
dưới đây là đoạn code tôi áp dụng trong dự án Android của tôi:
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();
}
}
}
bất cứ ai có thể đề xuất một giải pháp khả thi để giải quyết giá trị null trả về bởi getLastKnownLocation()? Mọi trợ giúp sẽ được đánh giá cao. Cảm ơn.
Cảm ơn. Điều này giải quyết được vấn đề. – Student
Đó là một mã tuyệt vời. Cảm ơn rất nhiều. –
Nó không phải là mã tuyệt vời .. đặt tất cả các mã bên trong một try/catch mà không có bất kỳ của nó một cách rõ ràng cần nó nó là xấu lập trình về nguyên tắc. Nếu bạn thực sự muốn có một đoạn mã tuyệt vời, hãy thử: https://web.archive.org/web/20100429083435/http://marakana.com/forums/android/android_examples/42.html –