android如何实现定位功能,android开发:location包实现定位的功能

申明:不要使用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) {

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值