系统定位
需要权限:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
获取LocationManager
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
设置参数和监听
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 100, listener);
* 第一个参数:定位类型
* 第二个参数:定位时间间隔
* 第三个参数:定位距离间隔
* 第四个参数:监听
当第3个参数不为0时,以第3个参数为依据;当第三个参数为0,已第2个参数为依据。
定位类型:(6.0上测试失败,没有获取到坐标,即使把targetSdkVersion
改成22,;5..1上测试成功。)
LocationManager.GPS_PROVIDER
LocationManager.NETWORK_PROVIDER
LocationManager.PASSIVE_PROVIDER
LocationListener listener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
//获取到坐标
LogUtil.d("onLocationChanged" + location.getProvider() + "," + location.getLongitude() + "," + location.getLatitude() + ","
+ location.getTime() + "," + location.getAltitude());
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
//GPS状态变化时触发
LogUtil.d("onStatusChanged," + provider + "," + status);
}
@Override
public void onProviderEnabled(String provider) {
//GPS开启时触发
LogUtil.d("onProviderEnabled," + provider);
}
@Override
public void onProviderDisabled(String provider) {
//GPS关闭时触发
LogUtil.d("onProviderDisabled," + provider);
}
};
AndroidUtilCode
的LocationUtils
LocationUtils.register(0, 0, new LocationUtils.OnLocationChangeListener() {
@Override
public void getLastKnownLocation(Location location) {
LogUtil.d("getLastKnownLocation," + location.getLatitude() + "," + location.getLongitude());
}
@Override
public void onLocationChanged(Location location) {
LogUtil.d("onLocationChanged," + location.getLatitude() + "," + location.getLongitude());
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
LogUtil.d("provider=" + provider + ",status=" + status);
}
});
LocationUtils.unregister();
其它
demo: http://git.oschina.net/AndroidSystemService/locationmanager01
android 的三种定位方式