我意识到 OP 已经接受了上述答案,但我感觉 OP 想要一个更简单的答案。
我假设 OP 有一个带有 Activity 的 android 应用程序。我这样声明我的:
public class HelloAndroidActivity extends Activity implements LocationListener {
OP 对生命周期方法如何工作以及何时应该完成工作感到困惑。我的 Resume 和 Pause 方法如下所示:
@Override
protected void onPause() {
((LocationManager)getSystemService(Context.LOCATION_SERVICE)).removeUpdates(this);
super.onPause();
}
@Override
protected void onResume() {
((LocationManager)getSystemService(Context.LOCATION_SERVICE)).requestLocationUpdates(LocationManager.GPS_PROVIDER, 5 * 1000, 1, this);
super.onResume();
}
请注意,我的 onResume 要求在有位置更新时通知我,而 onPause 方法要求不再通知我。您应该注意不要以小于您真正需要的时间间隔要求更新,否则您会耗尽电池电量。
由于活动实现了 LocationListener 我的 onLocationChanged 方法如下所示:
@Override
public void onLocationChanged(Location location) {
// Update the location fields
((EditText)findViewById(R.id.latField)).setText(Double.toString(location.getLatitude()));
((EditText)findViewById(R.id.longField)).setText(Double.toString(location.getLongitude()));
}
这只是获取新位置并更新我在我的活动中拥有的一些文本 EditText 字段。我唯一需要做的就是将 GPS 权限添加到我的清单中:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
因此,如果我要问如何开始使用位置管理器和位置服务,这就是我要开始的方式。我不想从公认的答案中拿走任何东西,我只是认为在 onResume 和 onLocationMethodChanged 方法中应该做什么存在根本性的误解。