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