【发布时间】:2014-05-04 03:42:18
【问题描述】:
这是我需要做的。我需要启动我的应用程序并单击一个按钮,我需要显示当前坐标,即纬度和经度。我遵循this 教程并使用以下代码来达到我的目的:
public class MainActivity extends Activity {
public double latitude;
public double longitude;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
@Override
protected void onStart() {
super.onStart();
final TextView latValueLabel = (TextView)findViewById(R.id.latLabel);
final TextView lonValueLabel = (TextView)findViewById(R.id.lonLabel);
Button setButton = (Button)findViewById(R.id.set_button);
setButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
latValueLabel.setText(String.valueOf(latitude));
lonValueLabel.setText(String.valueOf(longitude));
}
});
}
private class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if(location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
(仅复制粘贴部分代码,请忽略任何未闭合的括号或类似内容。)
它会随着位置的变化不断地获取纬度经度并将其存储到两个double变量latitude和longitude中,当单击setButton时,它会显示最后存储的纬度值。那将是用户的当前位置。现在的问题是,我启动了应用程序,但仍然停留在启动应用程序的确切位置,我单击了设置按钮。但是当时位置并没有改变,所以纬度和经度显示为零,这是双变量的默认值。我需要带着设备四处走走,以便在获得实际坐标之前更改位置。如何在应用启动后立即获得经纬度?
【问题讨论】:
-
使用
locationManager.getLastKnownLocation(... )初始化经纬度值。
标签: android gps location locationmanager locationlistener