当显示给用户位置时,经纬度不能作为信息显示,而是要显示一个地址,比如某某街道、某某社区。这是就要用到地理编码和反编码。地理编码是将一个地址转换为经纬度坐标,反之成为反编码。
当要实现地理编码和反编码时,需要ACCESS_FINE_LOCATION权限。
显示地址简单的UML类图如下:
反解码的过程是同步的,解码过程可能会很慢。这时为了避免ANR,不要在UI线程中调用,所以另外开了一个IntentService单独处理。IntentService的操作是在后台进程处理的,可以不影响界面响应。AsyncTask也可以运行后台操作,但是只能作为简单后台操作,要是操作很耗时,避免用AsyncTask。因为在Acitivity重新创建的时候(比如屏幕旋转)AsyncTask不能保留UI的引用(???疑问,IntentService能够保留???待测试),并且Activity重新创建的时候IntentService不会被重新创建,依旧能够在后台执行直到结束。
在geocoding过程中,需要用到类Geocoder:
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
构造函数为public Geocoder (Context context, Locale locale)或者public Geocoder (Context context)。
其中为了获得地址,可以调用public List<Address> getFromLocation (double latitude, double longitude, int maxResults)
,maxResults表示最大的结果数,官方推荐1-5。同样,地理编码可以调用函数public List<Address> getFromLocationName (String locationName, int maxResults, double lowerLeftLatitude, double lowerLeftLongitude, double upperRightLatitude, double upperRightLongitude)
。