2013-04-14 34 views
21

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.

Trả lời

42

các getLastKnownLocation() này sẽ trả về vị trí cuối cùng được biết đến ... sau khi bạn cài đặt lại ứng dụng nó sẽ không có bất kỳ vị trí cuối cùng được biết đến ... vì vậy nó sẽ dẫn đến NPE ... thay vì sử dụng mã dưới đây

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; 
} 

Nó làm việc cho tôi ... nên làm việc cho bạn quá ...

+0

Cảm ơn. Điều này giải quyết được vấn đề. – Student

+0

Đó là một mã tuyệt vời. Cảm ơn rất nhiều. –

+15

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 –

1

bạn chỉ cần thêm dòng thêm một vào mã

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

nếu vị trí == null?Làm thế nào để có được vị trí chính xác –

+0

chờ đợi những gì sai với bạn, tôi không biết chính xác những gì bạn đang cố gắng để trả lời. Câu hỏi đặt ra ở đây là có ai đó nói cho anh ta giải pháp, làm thế nào để loại bỏ đối tượng null này được trả về phương thức getLastKnownLocation (PROVIDER). Không hiển thị thông báo chúc mừng, không có bất kỳ đề xuất nào cần làm tiếp theo. – Khay

0

Hãy thử Sau mã

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

Không trả lời được vấn đề. –

-1

Tôi gặp vấn đề tương tự sau khi cài đặt lại thông qua nhật thực. Tôi đã giải quyết việc chuyển sang cài đặt Android/Quyền bảo mật/ứng dụng và xác nhận quyền đối với ứng dụng.

+2

Đó không phải là cách bạn cần để yêu cầu người dùng cấp các quyền đó trong thời gian chạy. [để biết thêm thông tin, hãy kiểm tra điều này] (https://developer.android.com/guide/topics/security/permissions.html#normal-dangerous) – kId

1

Giải pháp này là cải tiến nhỏ của tôi đối với mã @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(); 
    } 

Thưởng thức

Các vấn đề liên quan