在Android中接收GPS信息?

时间:2011-07-27 08:37:56

标签: android gps

我以前收到的GPS信息代码如下。应用程序错误是一部真正的手机。我认为应用程序的问题必须等待Gps接收它。我怎么能这样做?

    public class Main extends Activity {

    TextView text;
    Location currentLocation;
    double latitude;
    double longitude;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        text = (TextView)findViewById(R.id.text);

        LocationManager locationManager = 
            (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);

        LocationListener locationListener = new LocationListener() {
            public void onLocationChanged(Location location) {
                updateLocation(location);
            }
            public void onStatusChanged(
                    String provider, int status, Bundle extras) {}
            public void onProviderEnabled(String provider) {}
            public void onProviderDisabled(String provider) {}
        };

        locationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER, 1000, 1, locationListener);

        Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        latitude=location.getLatitude();
        longitude=location.getLongitude();

        addressText.setText("Latitude: "+latitude+" \n"+"Longitude: "+longitude);


void updateLocation(Location location){
        currentLocation = location;
        latitude = currentLocation.getLatitude();
        longitude = currentLocation.getLongitude();
    }
    }

2 个答案:

答案 0 :(得分:0)

我相信官方指南很好地解释了这一点。请看一下:http://developer.android.com/guide/topics/location/obtaining-user-location.html

答案 1 :(得分:0)

如果没有最后知道GPS的位置,这将返回null。

   Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

您需要等到GSP获得位置修复,才能通过调用onLocationChanged为您提供位置。您可以添加GPS状态监听器以查明何时发生这种情况。

在onCreate中添加:

locationManager.addGpsStatusListener(locationListener);

将此方法添加到locationListener:

@Override
public void onGpsStatusChanged(int event) {
    switch (event) {
    case GpsStatus.GPS_EVENT_FIRST_FIX:
        Log.d("GPSStatus", "GPS First Fix");
        break;
    case GpsStatus.GPS_EVENT_STARTED:
        Log.d("GPSStatus", "GPS Started");
        break;
    case GpsStatus.GPS_EVENT_STOPPED:
        Log.d("GPSStatus", "GPS Stopped");
        break;
    }
}

您还应该在请求位置更新之前检查GPS是否已启用。

    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))