Android获取用户位置

时间:2013-07-04 05:56:49

标签: android android-location

我正在构建一个需要获取用户位置的应用程序。由于我没有很多关于android的经验,我现在正在阅读有关如何让事情发挥作用的信息。

我已经为学习目的创建了一个测试应用程序。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    latitudeField = (TextView) findViewById(R.id.latitude);
    longitudeField = (TextView) findViewById(R.id.longitude);

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

    Criteria criteria = new Criteria();
    provider = locationManager.getBestProvider(criteria, false);
    Location location = locationManager.getLastKnownLocation(provider);

    if (location != null) {
        onLocationChanged(location);
    } else {
        latitudeField.setText("Latitute not available");
        longitudeField.setText("Longitude not available");
    }
}

@Override
public void onResume() {
    super.onResume();
    locationManager.requestLocationUpdates(provider, 400, 1, this);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

public void onPause() {
    super.onPause();
    locationManager.removeUpdates(this);
}


@Override
public void onLocationChanged(Location location) {
    int lat = (int) (location.getLatitude());
    int lng = (int) (location.getLongitude());
    latitudeField.setText(String.valueOf(lat));
    longitudeField.setText(String.valueOf(lng));
}

但我读到使用getLastKnownLocation()并不是最好的方法,因为如果你让手机进入睡眠状态,去另一个城市,你将无法获得位置更新。 您建议使用什么?

1 个答案:

答案 0 :(得分:0)

我建议您使用 GPSTracker 。即使您将手机置于睡眠状态或关闭/打开手机,也可以根据需要为您提供绝对位置。

相关问题