Welcome to android location using google play services example. Today we will learn how to use Google Play services API to retrieve your mobile location with example app.

欢迎使用Google Play服务示例访问Android位置。 今天,我们将学习如何通过示例应用程序使用Google Play服务API来检索您的移动位置。

Android Location API概述 (Android Location API Overview)

In the previous tutorial, we retrieved the user’s location using Android’s Location API that was available since Android’s API 1. So why was there a need for introducing Google Play Location Services? Why hasn’t Google enhanced Android’s Location API? What are the advantages of Google Play Location Services over the default Android Location API? Let’s discuss these questions to get a clear idea.

在上一教程中,我们使用了Android的位置API(自Android的API 1开始提供)来检索用户的位置。那么为什么需要引入Google Play定位服务? Google为什么没有增强Android的Location API? 与默认的Android Location API相比,Google Play定位服务有哪些优势? 让我们讨论这些问题以获得清晰的想法。

需要引入Google Play定位服务 (Need for introducing Google Play Location Services)

The Google Location Services API, part of Google Play Services, provides a more powerful, high-level framework that automates tasks such as location provider choice and power management. Furthermore, it provides new features such as user’s activity detection that wasn’t available in the Android Framework’s Location API. Currently, Google provides 5 user states which are In Vehicle, On Bicycle, On Foot, Still, and Tilting, which are good enough to detect user’s activity, and to provide right content according to user’s status.
Another feature it provides is Geofencing API that is used to notify a user entering or exiting a particular area.
The above advantages clearly indicate why Google Location Services API(also known as FusedLocationProviderApi) is Google’s recommended way of getting a user’s location. It provides the best accuracy based on our needs.

作为Google Play服务的一部分的Google Location Services API提供了功能更强大的高级框架,该框架可自动执行诸如位置提供商选择和电源管理之类的任务。 此外,它提供了新功能,例如Android Framework的Location API中不提供的用户活动检测。 目前,Google提供了5种用户状态,分别是“车辆内”“自行车上”“步行上” ,“ 静止 ”和“ 倾斜” ,这些状态足以检测用户的活动并根据用户的状态提供正确的内容。
它提供的另一个功能是Geofencing API ,用于通知用户进入或离开特定区域。
上述优势清楚地说明了为什么Google推荐使用Google Location Services API (也称为FusedLocationProviderApi )来获取用户位置。 它可以根据我们的需求提供最佳的准确性。

Google为什么没有增强Android的Location API? (Why hasn’t Google enhanced Android’s Location API?)

From a technical point of view, Google hasn’t improved Android’s Location API since Android has an independent update roll-out feature that lies in the hands of the smartphone manufacturer. Google has less control over it and hence decided to shift to a new API instead.

从技术角度来看,由于Android具有独立的更新推出功能(由智能手机制造商掌握),因此Google并未改进Android的Location API。 Google对它的控制较少,因此决定改用新的API。

There are few important classes that are used to get the location:

有几个重要的类可用于获取位置:

  • LocationRequest : A data object that contains quality of service parameters for requests to the FusedLocationProviderApi. LocationRequest objects are used to request a quality of service for location updates from the FusedLocationProviderApi.LocationRequest :一个数据对象,其中包含对FusedLocationProviderApi的请求的服务质量参数。 LocationRequest对象用于从FusedLocationProviderApi请求位置更新的服务质量。
  • FusedLocationProviderApi : The main entry point for interacting with the fused location provider. The methods must be used in conjunction with a GoogleApiClient client which we’ll look into shortly.FusedLocationProviderApi :与融合的位置提供程序进行交互的主要入口点。 这些方法必须与GoogleApiClient客户端结合使用,我们将在稍后介绍。
  • com.google.android.gms.location.LocationListener : The LocationListener interface is used for receiving notifications from the FusedLocationProviderApi when the location has changed. The method onLocationChanged is invoked if the LocationListener has been registered with the location client using the requestLocationUpdates(GoogleApiClient, LocationRequest, LocationListener) or requestLocationUpdates(GoogleApiClient, LocationRequest, LocationListener, Looper) methods.com.google.android.gms.location.LocationListener :位置更改后, LocationListener接口用于从FusedLocationProviderApi接收通知。 如果已使用requestLocationUpdates(GoogleApiClient, LocationRequest, LocationListener)requestLocationUpdates(GoogleApiClient, LocationRequest, LocationListener, Looper)方法向位置客户端注册了LocationListener,则调用requestLocationUpdates(GoogleApiClient, LocationRequest, LocationListener, Looper)方法。

To use Google Play’s Location Services API we need to call GoogleAPIClient first.

要使用Google Play的位置服务API,我们需要先调用GoogleAPIClient。

GoogleAPIClient (GoogleAPIClient)

GoogleAPIClient allows us to call multiple Google APIs using a single call.
Following is an example snippet to invoke the GoogleAPIClient with two APIs : Location Services and Drive API.

GoogleAPIClient允许我们使用一个调用来调用多个Google API。
以下是使用两个API调用GoogleAPIClient的示例代码段:Location Services和Drive API。

GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(LocationServices.API).addApi(Drive.API).addScope(Drive.SCOPE_FILE).addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();mGoogleApiClient.connect();

GoogleApiClient.ConnectionCallbacks and GoogleApiClient.OnConnectionFailedListener are implemented for addConnectionCallbacks and addOnConnectionFailedListener. onConnected() method that belongs to the GoogleApiClient.ConnectionCallbacks interface gets invoked when connections to all the APIs are established. onConnectionFailed() that belongs to GoogleApiClient.OnConnectionFailedListener interface is called in case of connection failure.

为addConnectionCallbacksaddOnConnectionFailedListener实现了GoogleApiClient.ConnectionCallbacksGoogleApiClient.OnConnectionFailedListener 。 建立与所有API的连接后,将调用属于GoogleApiClient.ConnectionCallbacks接口的onConnected()方法。 连接失败时,将调用属于GoogleApiClient.OnConnectionFailedListener接口的onConnectionFailed()

项目结构 (Project Structure)

码 (Code)

Add the following dependency in the build.gradle file.

在build.gradle文件中添加以下依赖项。

compile 'com.google.android.gms:play-services:9.8.0

compile 'com.google.android.gms:play-services:9.8.0

Add the following permissions in the AndroidManifest.xml file.

在AndroidManifest.xml文件中添加以下权限。

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

The activity_main.xml is given below.

下面给出activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"xmlns:tools="https://schemas.android.com/tools"android:id="@+id/activity_main"android:layout_width="match_parent"android:layout_height="match_parent"android:paddingBottom="@dimen/activity_vertical_margin"android:paddingLeft="@dimen/activity_horizontal_margin"android:paddingRight="@dimen/activity_horizontal_margin"android:paddingTop="@dimen/activity_vertical_margin"tools:context="com.journaldev.fusedlocationprovider.MainActivity"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Current Location"android:textAppearance="@style/TextAppearance.AppCompat.Display1"android:layout_centerVertical="true"android:id="@+id/current_location"android:layout_centerHorizontal="true" /><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerHorizontal="true"android:textSize="18sp"android:id="@+id/latLng"android:layout_below="@+id/current_location"/></RelativeLayout>

The MainAcitivity.java is given below.

MainAcitivity.java在下面给出。

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener, LocationListener {Location mLocation;TextView latLng;GoogleApiClient mGoogleApiClient;private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;private LocationRequest mLocationRequest;private long UPDATE_INTERVAL = 15000;  /* 15 secs */private long FASTEST_INTERVAL = 5000; /* 5 secs */private ArrayList permissionsToRequest;private ArrayList permissionsRejected = new ArrayList();private ArrayList permissions = new ArrayList();private final static int ALL_PERMISSIONS_RESULT = 101;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);latLng = (TextView) findViewById(R.id.latLng);permissions.add(ACCESS_FINE_LOCATION);permissions.add(ACCESS_COARSE_LOCATION);permissionsToRequest = findUnAskedPermissions(permissions);//get the permissions we have asked for before but are not granted..//we will store this in a global list to access later.if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {if (permissionsToRequest.size() > 0)requestPermissions(permissionsToRequest.toArray(new String[permissionsToRequest.size()]), ALL_PERMISSIONS_RESULT);}mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(LocationServices.API).addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();}private ArrayList findUnAskedPermissions(ArrayList wanted) {ArrayList result = new ArrayList();for (String perm : wanted) {if (!hasPermission(perm)) {result.add(perm);}}return result;}@Overrideprotected void onStart() {super.onStart();if (mGoogleApiClient != null) {mGoogleApiClient.connect();}}@Overrideprotected void onResume() {super.onResume();if (!checkPlayServices()) {latLng.setText("Please install Google Play services.");}}@Overridepublic void onConnected(@Nullable Bundle bundle) {if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {// TODO: Consider calling//    ActivityCompat#requestPermissions// here to request the missing permissions, and then overriding//   public void onRequestPermissionsResult(int requestCode, String[] permissions,//                                          int[] grantResults)// to handle the case where the user grants the permission. See the documentation// for ActivityCompat#requestPermissions for more details.return;}mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);if(mLocation!=null){latLng.setText("Latitude : "+mLocation.getLatitude()+" , Longitude : "+mLocation.getLongitude());}startLocationUpdates();}@Overridepublic void onConnectionSuspended(int i) {}@Overridepublic void onConnectionFailed(@NonNull ConnectionResult connectionResult) {}@Overridepublic void onLocationChanged(Location location) {if(location!=null)latLng.setText("Latitude : "+location.getLatitude()+" , Longitude : "+location.getLongitude());}private boolean checkPlayServices() {GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);if (resultCode != ConnectionResult.SUCCESS) {if (apiAvailability.isUserResolvableError(resultCode)) {apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST).show();} elsefinish();return false;}return true;}protected void startLocationUpdates() {mLocationRequest = new LocationRequest();mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);mLocationRequest.setInterval(UPDATE_INTERVAL);mLocationRequest.setFastestInterval(FASTEST_INTERVAL);if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {Toast.makeText(getApplicationContext(), "Enable Permissions", Toast.LENGTH_LONG).show();}LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);}private boolean hasPermission(String permission) {if (canMakeSmores()) {if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {return (checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED);}}return true;}private boolean canMakeSmores() {return (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1);}@TargetApi(Build.VERSION_CODES.M)@Overridepublic void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {switch (requestCode) {case ALL_PERMISSIONS_RESULT:for (String perms : permissionsToRequest) {if (!hasPermission(perms)) {permissionsRejected.add(perms);}}if (permissionsRejected.size() > 0) {if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {if (shouldShowRequestPermissionRationale(permissionsRejected.get(0))) {showMessageOKCancel("These permissions are mandatory for the application. Please allow access.",new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {requestPermissions(permissionsRejected.toArray(new String[permissionsRejected.size()]), ALL_PERMISSIONS_RESULT);}}});return;}}}break;}}private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {new AlertDialog.Builder(MainActivity.this).setMessage(message).setPositiveButton("OK", okListener).setNegativeButton("Cancel", null).create().show();}@Overrideprotected void onDestroy() {super.onDestroy();stopLocationUpdates();}public void stopLocationUpdates(){if (mGoogleApiClient.isConnected()) {LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);mGoogleApiClient.disconnect();}}
}

mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); is used to get the last known location from the location services.

mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); 用于从定位服务中获取最新的已知位置。

Following is the output when the application is run on a genymotion emulator.

以下是在genymotion模拟器上运行应用程序时的输出。

Our emulator can’t fetch the location since Google Play services isn’t installed.
Let’s see what the output looks like on a smartphone.

The Latitude and Longitude texts in the above application are updated every 5-15 seconds.

由于未安装Google Play服务,因此我们的模拟器无法获取位置。
让我们看看智能手机上的输出是什么样子。

上述应用程序中的纬度和经度文本每5-15秒更新一次。

This brings an end to this tutorial. You can download the Android FusedLocationProvider Project from the link below.

本教程到此结束。 您可以从下面的链接下载Android FusedLocationProvider项目

Download Android Location Google Play API Project下载Android Location Google Play API项目

翻译自: https://www.journaldev.com/13347/android-location-google-play-services

使用Google Play服务的Android定位相关推荐

  1. Android从零开始:Google Play服务

    Google Play服务库使Android开发人员可以轻松连接并使用Google支持的功能,并向后兼容新功能. 使用Google Play服务有两个主要部分,即Google服务后端和客户端应用. 在 ...

  2. Android使用Google Map服务 - 根据GPS信息在地图上定位

    Android使用Google Map服务 - 根据GPS信息在地图上定位 自暑假7月7日开始,到今天的8月7日,整个一个月,我总算是学到了Google Map这部分的内容.原本挺兴奋的,却被注册ap ...

  3. Android 定位服务(Location-Based Services)

    Android定位服务融合了GPS定位.移动通信.导航等多种技术,提供与空间位置相关的综合应用服务.近些年来,基于位置的服务发展更为迅速,涉及商务.医疗.工作和生活的各个方面,为用户提供定位.追踪和敏 ...

  4. android 定位服务 耗电吗,关于Android的定位服务

    今天因为工作须要,把以前编写的一个GPS测试法度榜样拿出来从新修改了一下.这个法度榜样说起来竽暌剐些汗青了,是我11年编写的,那时刻学了Android开辟没多久,算是一个实验性的作品.如今工作须要,从 ...

  5. Android 集成google map,Markers ,定位,聚合

    集成谷歌地图 前期准备 1.注册谷歌账号,然后再开发者平台登录 开发者平台传送门(需翻墙) 谷歌地图的文档 2.进入控制台,新建项目 3.此时成功创建项目,接下来是添加API,因为谷歌将谷歌地图的功能 ...

  6. android 定位服务注册,AndroidAPI申请密钥 - GeoLocation

    1. 简介 为了给用户提供更优质的服务,Android平台定位 SDK自v4.0版本开始引用了Key验证体系.因此,当您选择使用v4.0及之后版本的定位SDK时,需要先申请且配置Key,并在程序相应位 ...

  7. Android技术知识点:如何通过 Android Studio 和 Google Play 服务使用可下载字体

    介绍 您可以将应用设置为使用 Android Studio 3.0 或更高版本来下载字体. 为帮助您开始使用可下载字体功能,您可以使用 Google Play 服务提供的字体提供程序. 注意 设备必须 ...

  8. Android 模拟器一键获取root权限 一键安装Google play 服务

    最近要做一个集成地图的应用,最初准备使用高德地图或者百度地图,后来发现这两者均不适合我所开发的应用,因为是一个国际化的APP,最后决定使用Google地图.但是问题又来了,官方API写道在使用谷歌地图 ...

  9. android 定位的几种方式介绍

    [地理位置] android 定位的几种方式介绍 开发中对于地图及地理位置的定位是我们经常要用地,地图功能的使用使得我们应用功能更加完善,下面 www.androidkaifa.com 总结了一下网络 ...

最新文章

  1. Spring Cloud原理
  2. Hadoop中RPC机制详解之Server端
  3. RUNOOB python练习题17
  4. php增加mysql用户_mysql 增加用户
  5. Linux下查看显卡PCIE速率x16x8x4及设定
  6. 简单易懂设计模式——简单工厂模式
  7. exp-小写字母表导出问题?
  8. pytorch 与numpy 部分操作的对应关系
  9. JavaWeb开发通过Socket编程实现网页访问(附源代码)
  10. Python——查看帮助手册
  11. PHP - 主流开发框架 - 介绍
  12. NCBI数据库以及常用编号
  13. Rob Knight: PCR不需要做三个平行再混合!
  14. 浩方对战平台原理分析
  15. 学完了Hadoop,我总结了这些重点
  16. 云服务器部署 Web 项目
  17. Padded优化LinkedTransferQue并发性能是错误方向
  18. mtr--- 网络诊断工具
  19. 分销与供应链电子元器件采购需要掌握哪些基础知识?
  20. 美国大学计算机专业排名2014,2014USNews美国大学研究生计算机专业排名

热门文章

  1. Java零基础系列003——变量
  2. IOS开发学习----给表视图设置缩进级别
  3. 在网站中使用Session的简单例子
  4. [转帖] 资本的力量
  5. 页面校验请求MmEwMD(转载)
  6. SpringBoot私人学习笔记
  7. 与我们息息相关的internet服务(2)---WWW服务
  8. Cordova开发总结(插件篇)
  9. python3-day4(re正则表达式,冒泡)
  10. 收藏个支持进度条与文件拖拽上传的js File Uploader