申明:不要使用23以上的API,因为多了一个权限审核,会抛出异常,我今天就是因为Android Studio自动设置成23的API了,导致异常。
开发定位的功能很简单,首先获取LocationManager服务对象:
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
然后使用LocationManager对象的getLastKnownLocation方法返回一个Location对象,Location包含了经度、维度、海拔、速度等等信息,对,这就是我们要的。
代码:
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
StringBuffer sb = new StringBuffer();
if(location!=null) {
sb.append("经度:" + location.getLatitude() + " ");
sb.append("纬度:" + location.getLongitude() + " ");
sb.append("速度:" + location.getSpeed() + " ");
sb.append("提供者:" + location.getProvider() + " ");
sb.append("精准度:" + location.getAccuracy() + " ");
sb.append("海拔:" + location.getAltitude() + " ");
sb.append("getBearing:" + location.getBearing() + " ");
sb.append("getElapsedRealtimeNanos:" + location.getElapsedRealtimeNanos() + " ");
}
text.setText( sb);
如果我们需要在特定的时间内更新GPS位置,那么我们需要创建监听器LocationListener,LocationListener可以为我们更新位置信息,使用LocationManager方法:
public voidrequestLocationUpdates (String provider, long minTime, float minDistance, LocationListenerlistener)
Register for location updates using the named provider, and a pending intent.
Parameters
provider
the name of the provider with which to register
minTime
minimum time interval between location updates, in milliseconds
minDistance
minimum distance between location updates, in meters
listener
a
监听器的代码:
new LocationListener() {
@Override
public void onLocationChanged(Location location) {