【发布时间】:2016-03-09 16:52:26
【问题描述】:
我的应用不需要即时位置更新。只有在(1)应用程序启动时才需要位置; (2)打开特定的活动/片段; (3)用户点击“获取我的位置”按钮。
标准是:当需要时,位置必须快速到达,即使它是粗略的(如果可能的话)最低电池消耗。我打算使用以下方法:
public void getLocation() {
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
if(location != null) {
//save the location to shared prefs to use when needed
return;
}
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location != null) {
//save the location to shared prefs to use when needed
return;
}
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null) {
//save the location to shared prefs to use when needed
return;
}
// if reached that point the location cannot be got!!
}
计划是在每次应用启动、特定页面被激活或用户想要获取当前位置时调用该方法。除非这些操作触发位置更新,否则旧位置或无位置就足够了。这种方法有意义吗?我可以在不实现位置侦听器和/或调用方法“requestLocationUpdates()”的情况下做到这一点吗?我担心的是“getLastKnownLocation()”在调用时可能不会给出当前位置,因为我不确定来自提供商的“最后已知位置”更新的频率或条件。
非常感谢任何建议和cmets。
【问题讨论】:
-
将位置存储在共享首选项中并在必要时检索它们似乎是个好主意