显示位置地址

    获取最后可知位置和课程描述了如何以一个Location对象的形式获取用户的位置信息,这个位置信息包括了经纬度。尽管经纬度对计算地理距离和在地图上显示位置很有用,但是更多情况下位置的地址更有用。例如,如果我们想让用户知道他们在哪里,那么一个街道地址比地理坐标(经度/纬度)更加有意义。

    使用 Android 框架位置 APIs 的 类,我们可以将地址转换成相应的地理坐标。这个过程叫做地理编码。或者,我们可以将地理位置转换成相应的地址。这种地址查找功能叫做反向地理编码

    这节课介绍了如何用 getFromLocation() 方法将地理位置转换成地址。这个方法返回与制定经纬度相对应的估计的街道地址。

    设备的最后可知位置对于地址查找功能是很有用的基础。介绍了如何通过调用 fused location provider 提供的 ) 方法找到设备的最后可知位置。

    为了访问 fused location provider,我们需要创建一个 Google Play services API client 的实例。关于如何连接 client,请见连接 Google Play Services

    为了让 fused location provider 得到一个准确的街道地址,在应用的 manifest 文件添加位置权限 ,如下所示:

    类的 getFromLocation() 方法接收一个经度和纬度,返回一个地址列表。这个方法是同步的,可能会花很长时间来完成它的工作,所以我们不应该在应用的主线程和 UI 线程里调用这个方法。

    类提供了一种结构使一个任务在后台线程运行。使用这个类,我们可以在不影响 UI 响应速度的情况下处理一个长时间运行的操作。注意到,AsyncTask 类也可以执行后台操作,但是它被设计用于短时间运行的操作。在 activity 重新创建时(例如当设备旋转时), 不应该保存 UI 的引用。相反,当 activity 重建时,不需要取消 IntentService

    定义一个继承 的类 FetchAddressIntentService。这个类是地址查找服务。这个 Intent 服务在一个工作线程上异步地处理一个 intent,并在它离开这个工作时自动停止。Intent 外加的数据提供了服务需要的数据,包括一个用于转换成地址的 Location 对象和一个用于处理地址查找结果的 对象。这个服务用一个 Geocoder 来获取位置的地址,并且将结果发送给 。

    1. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    2. package="com.google.android.gms.location.sample.locationaddress" >
    3. <application
    4. ...
    5. <service
    6. android:name=".FetchAddressIntentService"
    7. android:exported="false"/>
    8. </application>
    9. ...
    10. </manifest>

    Note:manifest 文件里的 <service> 节点不需要包含一个 intent filter,这是因为我们的主 activity 通过指定 intent 用到的类的名字来创建一个隐式的 intent。

    将一个地理位置传换成地址的过程叫做反向地理编码。通过实现 FetchAddressIntentService 类的 onHandleIntent()) 来执行 intent 服务的主要工作,即反向地理编码请求。创建一个 对象来处理反向地理编码。

    一个区域设置代表一个特定的地理上的或者语言上的区域。Locale 对象用于调整信息的呈现方式,例如数字或者日期,来适应区域设置表示的区域的约定。传一个 Locale 对象到 对象,确保地址结果为用户的地理区域作出了本地化。

    1. @Override
    2. protected void onHandleIntent(Intent intent) {
    3. Geocoder geocoder = new Geocoder(this, Locale.getDefault());
    4. ...
    5. }

    下一步是从 geocoder 获取街道地址,处理可能出现的错误,和将结果返回给请求地址的 activity。我们需要两个分别代表成功和失败的数字常量来报告地理编码过程的结果。定义一个 Constants 类来包含这些值,如下所示:

    为了获取与地理位置相对应的街道地址,调用 getFromLocation(),传入位置对象的经度和纬度,以及我们想要返回的地址的最大数量。在这种情况下,我们只需要一个地址。geocoder 返回一个地址数组。如果没有找到匹配指定位置的地址,那么它会返回空的列表。如果没有可用的后台地理编码服务,geocoder 会返回 null。

    如下面代码介绍来检查下述这些错误。如果出现错误,就将相应的错误信息传给变量 errorMessage,从而将错误信息发送给发出请求的 activity:

    • No location data provided - Intent 的附加数据没有包含反向地理编码需要用到的 对象。
    • Invalid latitude or longitude used - Location 对象提供的纬度和/或者经度无效。
    • No geocoder available - 由于网络错误或者 IO 异常,导致后台地理编码服务不可用。
    • Sorry, no address found - geocoder 找不到指定纬度/经度对应的地址。

    使用 类中的 getAddressLine()) 方法来获得地址对象的个别行。然后将这些行加入一个地址 fragment 列表当中。其中,这个地址 fragment 列表准备好返回到发出地址请求的 activity。

    为了将结果返回给发出地址请求的 activity,需要调用 deliverResultToReceiver() 方法(定义于下面的)。结果由之前提到的成功/失败数字代码和一个字符串组成。在反向地理编码成功的情况下,这个字符串包含着地址。在失败的情况下,这个字符串包含错误的信息。如下所示:

    1. @Override
    2. protected void onHandleIntent(Intent intent) {
    3. String errorMessage = "";
    4. // Get the location passed to this service through an extra.
    5. Location location = intent.getParcelableExtra(
    6. Constants.LOCATION_DATA_EXTRA);
    7. ...
    8. List<Address> addresses = null;
    9. try {
    10. addresses = geocoder.getFromLocation(
    11. location.getLatitude(),
    12. // In this sample, get just a single address.
    13. 1);
    14. } catch (IOException ioException) {
    15. // Catch network or other I/O problems.
    16. errorMessage = getString(R.string.service_not_available);
    17. Log.e(TAG, errorMessage, ioException);
    18. } catch (IllegalArgumentException illegalArgumentException) {
    19. // Catch invalid latitude or longitude values.
    20. Log.e(TAG, errorMessage + ". " +
    21. "Latitude = " + location.getLatitude() +
    22. ", Longitude = " +
    23. location.getLongitude(), illegalArgumentException);
    24. }
    25. // Handle case where no address was found.
    26. if (addresses == null || addresses.size() == 0) {
    27. if (errorMessage.isEmpty()) {
    28. errorMessage = getString(R.string.no_address_found);
    29. Log.e(TAG, errorMessage);
    30. }
    31. deliverResultToReceiver(Constants.FAILURE_RESULT, errorMessage);
    32. } else {
    33. Address address = addresses.get(0);
    34. ArrayList<String> addressFragments = new ArrayList<String>();
    35. // Fetch the address lines using getAddressLine,
    36. // join them, and send them to the thread.
    37. for(int i = 0; i < address.getMaxAddressLineIndex(); i++) {
    38. addressFragments.add(address.getAddressLine(i));
    39. }
    40. Log.i(TAG, getString(R.string.address_found));
    41. deliverResultToReceiver(Constants.SUCCESS_RESULT,
    42. TextUtils.join(System.getProperty("line.separator"),
    43. addressFragments));
    44. }
    45. }

    Intent 服务最后要做的事情是将地址返回给启动服务的 activity 里的 ResultReceiver。这个 类允许我们发送一个带有结果的数字代码和一个包含结果数据的消息。这个数字代码说明了地理编码请求是成功还是失败。在反向地理编码成功的情况下,这个消息包含着地址。在失败的情况下,这个消息包含一些描述失败原因的文本。

    对于结果代码,使用已经传给 deliverResultToReceiver() 方法的 resultCode 参数的值。对于消息包的结构,连接 Constants 类的 RESULT_DATA_KEY 常量(定义与获取街道地址数据)和传给 deliverResultToReceiver() 方法的 message 参数的值。如下所示:

    1. public class FetchAddressIntentService extends IntentService {
    2. protected ResultReceiver mReceiver;
    3. ...
    4. private void deliverResultToReceiver(int resultCode, String message) {
    5. Bundle bundle = new Bundle();
    6. mReceiver.send(resultCode, bundle);
    7. }
    8. }

    上节课定义的 intent 服务在后台运行,同时,该服务负责提取与指定地理位置相对应的地址。当我们启动服务,Android 框架会实例化并启动服务(如果该服务没有运行),并且如果需要的话,创建一个进程。如果服务正在运行,那么让它保持运行状态。因为服务继承于 ,所以当所有 intent 都被处理完之后,该服务会自动停止。

    在我们应用的主 activity 中启动服务,并且创建一个 Intent 来把数据传给服务。我们需要创建一个显式的 intent,这是因为我们只想我们的服务响应该 intent。详细请见 。

    为了创建一个显式的 intent,需要为服务指定要用到的类名:。在 intent 附加数据中传入两个信息:

    • 一个用于处理地址查找结果的 ResultReceiver
    • 一个包含想要转换成地址的纬度和经度的 对象。

    下面的代码介绍了如何启动 intent 服务:

    当用户请求查找地理地址时,调用上述的 startIntentService() 方法。例如,用户可能会在我们应用的 UI 上面点击提取地址按钮。在启动 intent 服务之前,我们需要检查是否已经连接到 Google Play services。下面的代码片段介绍在一个按钮 handler 中调用 startIntentService() 方法。

    1. public void fetchAddressButtonHandler(View view) {
    2. // Only start the service to fetch the address if GoogleApiClient is
    3. // connected.
    4. if (mGoogleApiClient.isConnected() && mLastLocation != null) {
    5. startIntentService();
    6. }
    7. // If GoogleApiClient isn't connected, process the user's request by
    8. // setting mAddressRequested to true. Later, when GoogleApiClient connects,
    9. // launch the service to fetch the address. As far as the user is
    10. // concerned, pressing the Fetch Address button
    11. // immediately kicks off the process of getting the address.
    12. mAddressRequested = true;
    13. updateUIWidgets();
    14. }

    如果用户点击了应用 UI 上面的提取地址按钮,那么我们必须在 Google Play services 连接稳定之后启动 intent 服务。下面的代码片段介绍了调用 Google API Client 提供的 onConnected()) 回调函数中的 startIntentService() 方法。

    1. public class MainActivity extends ActionBarActivity implements
    2. ConnectionCallbacks, OnConnectionFailedListener {
    3. ...
    4. @Override
    5. public void onConnected(Bundle connectionHint) {
    6. // Gets the best and most recent location currently available,
    7. // which may be null in rare cases when a location is not available.
    8. mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
    9. mGoogleApiClient);
    10. if (mLastLocation != null) {
    11. // Determine whether a Geocoder is available.
    12. if (!Geocoder.isPresent()) {
    13. Toast.makeText(this, R.string.no_geocoder_available,
    14. Toast.LENGTH_LONG).show();
    15. return;
    16. }
    17. if (mAddressRequested) {
    18. startIntentService();
    19. }
    20. }
    21. }

    Intent 服务已经处理完地理编码请求,并用 将结果返回给发出请求的 activity。在发出请求的 activity 里,定义一个继承于 ResultReceiverAddressResultReceiver,用于处理在 FetchAddressIntentService 中的响应。

    结果包含一个数字代码(resultCode)和一个包含结果数据(resultData)的消息。如果反向地理编码成功的话, 会包含地址。如果失败,resultData 包含描述失败原因的文本。关于错误信息更详细的内容,请见