2

我尝试从 GPS 添加位置,但我总是得到空值。你能帮我看看我做错了什么吗?

我想始终在 onCreate 中接收位置。如果未收到位置,则显示“未收到提供者”而不是位置。问题是我总是收到消息。

//Location variables
private TextView gps;
private LocationManager locationManager;
private String locationProvider;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_upload_draw);
    initializeData();
}

private void initializeData()
{
    gps = (TextView) findViewById(R.id.GPS);
    locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

    locationProvider = locationManager.getBestProvider(new Criteria(), true);
    if(locationProvider!=null)
     {
        gps.setText("Upload image location: "+ locationProvider); 
     }
    else
    {
        gps.setText("Upload image location: No provider Found" );
    }

}


@Override
protected void onPause() {  
    super.onPause();
    locationManager.removeUpdates(this);
}

private void showLocation(Location location)
{
    if(location==null)
        gps.append("\nUnknown location");
    else
    {
        double lat = location.getLatitude();
        double lng = location.getLongitude();
        gps.append("\n\nLocation lat: " +lat+
                ", long: " + lng+"\n"
                + getAddress(lat, lng));
    }
}

public void onLocationChanged(Location location) {
    showLocation(location);     
}

public void onProviderDisabled(String provider) {
    gps.append("\nProvider Disabled: " +provider);
}

public void onProviderEnabled(String provider) {
    gps.append("\nProvider Enabled: " +provider);       
}

public void onStatusChanged(String provider, int status, Bundle extras) {
    gps.append("\nProvider Status Changed: " + provider+ ",status: "+
                status);
}

public String getAddress(double lat, double lng)
{
    Geocoder geocoder = new Geocoder(this);

    try {
        List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
        Address obj = addresses.get(0);
        String str  = obj.getCountryName();
        str+="\n" + obj.getCountryCode();
        str+="\n" + obj.getLocality(); //current city
        str+="\n" + obj.getAddressLine(0); 

        return str;         
    }
    catch (IOException e) {
        return "Error: "  +e.getMessage();
    }
}
4

1 回答 1

1

1)您需要向提供商请求更新:

newLocation = requestUpdatesFromProvider(
            LocationManager.GPS_PROVIDER, "error string");

2)注册一个监听器:

LocationListener listener = new LocationListener() {

@Override
public void onLocationChanged(Location location) {
//Do something

} );}
于 2012-09-24T10:43:27.157 回答