注:本文翻译自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()并返回地址。定义一个名字叫mAddressTextView对象,用来显示返回的地址,另外一个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. 显示一个位置地址的更多相关文章

  1. 【Android Developers Training】 102. 序言:让你的应用获知地点

    注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...

  2. 【Android Developers Training】 3. 构建一个简单UI

    注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...

  3. 【Android Developers Training】 101. 显示快速联系人挂件(Quick Contact Badge)

    注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...

  4. 【Android Developers Training】 28. 将用户带领到另一个应用

    注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...

  5. 【Android Developers Training】 4. 启动另一个Activity

    注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...

  6. 【Android Developers Training】 1. 创建一个Android项目工程

    注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...

  7. 【Android Developers Training】 93. 创建一个空验证器

    注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...

  8. 【Android Developers Training】 18. 重新创建一个Activity

    注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...

  9. 【Android Developers Training】 16. 暂停和恢复一个Activity

    注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...

随机推荐

  1. 一步步学习EF Core(3.EF Core2.0路线图)

    前言 这几天一直在研究EF Core的官方文档,暂时没有发现什么比较新的和EF6.x差距比较大的东西. 不过我倒是发现了EF Core的路线图更新了,下面我们就来看看 今天我们来看看最新的EF Cor ...

  2. Linux学习第三步(Centos7安装mysql5.7数据库)

    版本:mysql-5.7.16-1.el7.x86_64.rpm-bundle.tar 前言:在linux下安装mysql不如windows下面那么简单,但是也不是很难.本文向大家讲解了如何在Cent ...

  3. C#中string,char[],byte[]互相转换

    string 转换成 Char[] string ss = "我爱你,中国"; char[] cc = ss.ToCharArray(); Char[] 转换成string str ...

  4. 【Python 函数对象 命名空间与作用域 闭包函数 装饰器 迭代器 内置函数】

    一.函数对象 函数(Function)作为程序语言中不可或缺的一部分,但函数作为第一类对象(First-Class Object)却是 Python 函数的一大特性. 那到底什么是第一类对象(Firs ...

  5. 求一个二维整数数组最大子数组之和,时间复杂度为N^2

    本随笔只由于时间原因,我就只写写思想了 二维数组最大子数组之和,可以  引用  一维最大子数组之和 的思想一维最大子数组之和 的思想,在本博客上有,这里就不做多的介绍了 我们有一个最初的二维数组a[n ...

  6. 开涛spring3(3.1) - DI的配置使用

    3.1.1  依赖和依赖注入 传统应用程序设计中所说的依赖一般指“类之间的关系”,那先让我们复习一下类之间的关系: 泛化:表示类与类之间的继承关系.接口与接口之间的继承关系: 实现:表示类对接口的实现 ...

  7. Ubuntu上配置SQL Server Always On Availability Group(Configure Always On Availability Group for SQL Server on Ubuntu)

    下面简单介绍一下如何在Ubuntu上一步一步创建一个SQL Server AG(Always On Availability Group),以及配置过程中遇到的坑的填充方法. 目前在Linux上可以搭 ...

  8. JMETER 不同线程组 变量值 的参数传递

    线程组 1   在线程组1中使用__setProperty函数设置jmeter属性值(此值为全局变量值),将所需变量值如${token}设置为jmeter属性值,即newtoken,示例: 1.添加- ...

  9. opencv基础到进阶(1)

    Opencv是一个用户基础非常多的视觉开发库,可以用来实现人脸识别等功能,由于涉及到大量的调用与计算,所以对硬件的条件要求很高,并且还需要时时刻刻注意内存溢出这个问题,怎么样?很刺激吧. 从这篇文章开 ...

  10. 导入数据到mysql服务器上,报错,以及停止的解决办法

    两次都是因为磁盘不够,这次得以解决: =>下面是可能会用到的命令行: 1.查看磁盘占用大小: df -hl 发现:   从上面看出来,根目录 / 下的东西沾满了  /dev/sda1  但是 / ...