使用LocationManager 类的requestLocationUpdates() 在特定时间间隔内获取GPS 位置。查看this 供您参考。
请参阅以下代码 sn-p ,它将每 1 分钟获取用户当前的经纬度位置。
public Location getLocation() {
Location location = null;
try {
LocationManager locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
// Getting GPS status
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// If GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES,
this
);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
得到Latitude和Longitude后使用Geocoder获取详细地址。
public List<Address> getCurrentAddress() {
List<Address> addresses = new ArrayList<Address>();
Geocoder gcd = new Geocoder(mContext,Locale.getDefault());
try {
addresses = gcd.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
编辑:
在extends Service 的类中执行所有上述功能,以便即使应用程序关闭,它也可以跟踪用户位置。请参阅下面的示例
public final class LocationTracker extends Service implements LocationListener {
// Your code here
}