【Android Developers Training】 105. 显示一个位置地址
注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好。
原文链接:http://developer.android.com/training/location/display-address.html
前两节课程讲解了如何以Location对象的形式(包含经纬度的信息)来获取用户的当前地理位置信息。虽然经纬度信息对于计算距离或者显示一个地图位置很有用,但在很多情况下,当前地点的地址往往作用更大。
Android API提供了一个特性,它可以针对经纬度信息估计出用户所在的街道地址。这节课将讲解如何使用这一地址查询功能。
Note:
地址查询需要一个没有包括在核心Android框架中的后端服务。如果这个后端服务无法获取,Geocoder.getFromLocation()会返回一个空的list。辅助方法isPresent()在API 9及以上版本中可以获得,它可以用来检查后端服务是否可以获取。
下列章节中的样例代码均假设你的应用已经获取了当前地点,并将它以一个Location对象的形式存储于全局变量mLocation中。
一). 定义地址查询任务
要获取给定经纬度的地址信息,调用Geocoder.getFromLocation(),它会返回一个包含地址的list。该方法是同步的,并且会耗费较长的时间去执行,所以你应该在一个AsyncTask中的doInBackground()里面进行调用。
当你的应用在获取地址时,显示一个执行任务的标识告诉用户你的应用正在执行后台程序是有必要的。我们首先将这个标识的初始状态设置为android:visibility="gone",这可以使得它初始时不可见并且从布局层次结构中移除。当你开始地址查询时,你应该将它的可见性设置为“visible”。
下面的代码片段展示了如何在你的布局文件中添加一个ProgressBar:
<ProgressBar
android:id="@+id/address_progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:indeterminate="true"
android:visibility="gone" />
要创建一个后台任务,定义一个AsyncTask的子类,用来调用getFromLocation()并返回地址。定义一个名字叫mAddress的TextView对象,用来显示返回的地址,另外一个ProgressBar对象允许你可以对后台执行的标识进行控制,例如:
public class MainActivity extends FragmentActivity {
...
private TextView mAddress;
private ProgressBar mActivityIndicator;
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
mAddress = (TextView) findViewById(R.id.address);
mActivityIndicator =
(ProgressBar) findViewById(R.id.address_progress);
}
...
/**
* A subclass of AsyncTask that calls getFromLocation() in the
* background. The class definition has these generic types:
* Location - A Location object containing
* the current location.
* Void - indicates that progress units are not used
* String - An address passed to onPostExecute()
*/
private class GetAddressTask extends
AsyncTask<Location, Void, String> {
Context mContext;
public GetAddressTask(Context context) {
super();
mContext = context;
}
...
/**
* Get a Geocoder instance, get the latitude and longitude
* look up the address, and return it
*
* @params params One or more Location objects
* @return A string containing the address of the current
* location, or an empty string if no address can be found,
* or an error message
*/
@Override
protected String doInBackground(Location... params) {
Geocoder geocoder =
new Geocoder(mContext, Locale.getDefault());
// Get the current location from the input parameter list
Location loc = params[0];
// Create a list to contain the result address
List<Address> addresses = null;
try {
/*
* Return 1 address.
*/
addresses = geocoder.getFromLocation(loc.getLatitude(),
loc.getLongitude(), 1);
} catch (IOException e1) {
Log.e("LocationSampleActivity",
"IO Exception in getFromLocation()");
e1.printStackTrace();
return ("IO Exception trying to get address");
} catch (IllegalArgumentException e2) {
// Error message to post in the log
String errorString = "Illegal arguments " +
Double.toString(loc.getLatitude()) +
" , " +
Double.toString(loc.getLongitude()) +
" passed to address service";
Log.e("LocationSampleActivity", errorString);
e2.printStackTrace();
return errorString;
}
// If the reverse geocode returned an address
if (addresses != null && addresses.size() > 0) {
// Get the first address
Address address = addresses.get(0);
/*
* Format the first line of address (if available),
* city, and country name.
*/
String addressText = String.format(
"%s, %s, %s",
// If there's a street address, add it
address.getMaxAddressLineIndex() > 0 ?
address.getAddressLine(0) : "",
// Locality is usually a city
address.getLocality(),
// The country of the address
address.getCountryName());
// Return the text
return addressText;
} else {
return "No address found";
}
}
...
}
...
}
在下一章节将会向你展示如何在用户接口显示地址。
二). 定义一个显示结果的方法
doInBackground()返回的地址查询结果是一个String的类型。值被传递到onPostExecute()中,在这个方法里你将会对结果做进一步的处理。由于onPostExecute()方法是在UI线程中执行的,它可以用来更新用户接口;例如,它可以关闭进度条并且将结果显示给用户:
private class GetAddressTask extends
AsyncTask<Location, Void, String> {
...
/**
* A method that's called once doInBackground() completes. Turn
* off the indeterminate activity indicator and set
* the text of the UI element that shows the address. If the
* lookup failed, display the error message.
*/
@Override
protected void onPostExecute(String address) {
// Set activity indicator visibility to "gone"
mActivityIndicator.setVisibility(View.GONE);
// Display the results of the lookup.
mAddress.setText(address);
}
...
}
最后的步骤就是要运行地址查询了。
三). 执行查询任务
要获取地址,调用execute()方法。例如,下面的代码片段在用户点击了“获取地址”这一按钮后,启动地址查询:
public class MainActivity extends FragmentActivity {
...
/**
* The "Get Address" button in the UI is defined with
* android:onClick="getAddress". The method is invoked whenever the
* user clicks the button.
*
* @param v The view object associated with this method,
* in this case a Button.
*/
public void getAddress(View v) {
// Ensure that a Geocoder services is available
if (Build.VERSION.SDK_INT >=
Build.VERSION_CODES.GINGERBREAD
&&
Geocoder.isPresent()) {
// Show the activity indicator
mActivityIndicator.setVisibility(View.VISIBLE);
/*
* Reverse geocoding is long-running and synchronous.
* Run it on a background thread.
* Pass the current location to the background task.
* When the task finishes,
* onPostExecute() displays the address.
*/
(new GetAddressTask(this)).execute(mLocation);
}
...
}
...
}
在下一节课,我们将会讲解如何去定义感兴趣的地点并调用地理围栏,以及如何使用它来检测用户是否接近感兴趣的地点。
【Android Developers Training】 105. 显示一个位置地址的更多相关文章
- 【Android Developers Training】 102. 序言:让你的应用获知地点
注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...
- 【Android Developers Training】 3. 构建一个简单UI
注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...
- 【Android Developers Training】 101. 显示快速联系人挂件(Quick Contact Badge)
注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...
- 【Android Developers Training】 28. 将用户带领到另一个应用
注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...
- 【Android Developers Training】 4. 启动另一个Activity
注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...
- 【Android Developers Training】 1. 创建一个Android项目工程
注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...
- 【Android Developers Training】 93. 创建一个空验证器
注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...
- 【Android Developers Training】 18. 重新创建一个Activity
注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...
- 【Android Developers Training】 16. 暂停和恢复一个Activity
注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...
随机推荐
- 模板方法模式(Tempalte Method Pattern)
模板方法模式是类的行为模式.准备一个抽象类,将部分逻辑以具体方法以及具体构造函数的形式实现,然后声明一些抽象方法来迫使子类实现剩余的逻辑.不同的子类可以以不同的方式实现这些抽象方法,从而对剩余的逻辑有 ...
- 升讯威微信营销系统开发实践:(5) Github 源码:微信接口的 .NET 封装。
微信开发系列教程,将以一个实际的微信平台项目为案例,深入浅出的讲解微信开发.应用各环节的实现方案和技术细节. 本系列教程的最终目标是完成一个功能完善并达到高可用性能指标的微信管理软件,所以除了与微信本 ...
- Java Synchronization
Volatile Since Java 5 the volatile keyword guarantees more than just the reading from and writing to ...
- PHP 工厂模式 实例讲解
简单工厂模式:①抽象基类:类中定义抽象一些方法,用以在子类中实现②继承自抽象基类的子类:实现基类中的抽象方法③工厂类:用以实例化对象 看完文章再回头来看下这张图,效果会比较好 1 采用封装方式 2 3 ...
- .net后台获取DataTable数据,转换成json数组后传递到前台,通过jquery去操作json数据
一,后台获取json数据 protected void Page_Load(object sender, EventArgs e){ DataTable dt = DBhepler.GetDataT ...
- Linux系统下安装Mysql5.7.18教程收集分享
本人最近服务器新手入门,需要搭建一个在linux虚拟机上的服务器 第一天再装虚拟机,选的linux系统CentOS,一切顺利. 第二天,要给虚拟机装Mysql,但是需要用到命令行进行安装/操作等,我是 ...
- Centos7 最小系统安装Redis
最近想写一个调度系统,一顿查资料之后决定用Django+Celery+Redis实现,前面两个都已经有了,就缺一个Redis,所以准备安装一个Redis 获取Centos7并配置网络 获取Centos ...
- 汽车Vin码识别—— 一款二手车行业值得拥有的OCR识别软件
一.汽车Vin码识别产品描述 汽车Vin码识别系统,主要应用在智能手机IOS与Android两个平台中.前端扫描查询模式,无需联网,只需扫描汽车前挡风玻璃右下角的Vin码(车架号),即可轻松识别出车辆 ...
- 翻译Algorithms Unlocked
写在前面 本书是由<算法导论>(Introduction to Algorithms)的作者之一Thomas H. Cormen编写的适合对算法感兴趣但自身基础又不好的同学阅读.很多人评价 ...
- 关于cas server无法通过session持久化方式实现集群的问题
最近在搭建cas单点登录系统 ,在建立集群时发生一个问题. 搭建的环境是tomcat+tomcat-redis-session-manager+redis+cas 在对tomcat的session进行 ...