开发者

Receive GPS Information in Android?

I used to receive the GPS information of the code is as follows. The app error is a real phone. I think the problem of the application have to wait for Gps to receive it. How can I do this?

    public class Main extends Activity {

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

    @Override
    public void onCreate(Bundle savedI开发者_C百科nstanceState) {

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


I believe the official guide explains this quite well. Please take a look there: http://developer.android.com/guide/topics/location/obtaining-user-location.html


This will return null if there no last know location for the GPS.

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

You need to wait until the GSP has got a location fix for it to give you a location by calling onLocationChanged. You can add a GPS status listener to find out when this occurs.

In onCreate add:

locationManager.addGpsStatusListener(locationListener);

Add this method to 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;
    }
}

You should also check if GPS is enabled before requesting location updates.

    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜