【问题标题】:Android get users locationAndroid获取用户位置
【发布时间】:2013-07-04 05:56:48
【问题描述】:

我正在构建一个需要获取用户位置的应用程序。由于我对 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() 并不是最好的方法,因为如果你让手机进入睡眠状态,去另一个城市,你就不会得到你的位置更新。 您建议改用什么?

【问题讨论】:

  • 您正在更新请求。然后,当您更改位置时,会自动触发您的 onLocationChnaged()。所以这样你的位置纬度和经度就改变了
  • 对不起,我不太了解你...
  • 您已经覆盖了在您的位置更改时触发的 onLocationChanged 方法。换句话说,即使您的手机进入睡眠状态,您也会收到更新。
  • @Karlis,你的问题还没解决吗?

标签: android android-location


【解决方案1】:

我建议你使用 GPSTracker。即使您将手机置于睡眠状态或关闭/打开手机,这也会为您提供所需的绝对位置。

【讨论】:

    猜你喜欢
    • 2012-08-19
    • 1970-01-01
    • 2013-07-29
    • 2018-08-13
    • 2018-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    相关资源
    最近更新 更多