前言
预订出租车后,您是否注意到出租车在前往您的地址时在道路上移动?有各种应用程序使用某种定位服务。使用 GPS 更新位置是一个非常酷的功能。汽车的移动图标(以 Uber 为例)看起来很酷,作为一名 Android 开发人员,我们都曾想过在我们的移动应用程序中使用这些类型的功能,但在集成此功能时出现了某种错误。
所以,不用担心,在这篇文章中,我们将学习如何使用Fused Location API通过手机自带的 GPS 来获取 Android 设备的准确位置。我们将使用 GPS 显示手机的当前位置,每当手机位置更新时,更新后的位置就会显示在应用程序上。那么,让我们开始吧。
在此之前
在继续编码部分之前,我们需要了解位置权限。
位置权限
如果您想获取用户的当前位置,则必须将位置权限添加到您的应用程序。Android 提供以下位置权限:
- ACCESS_COARSE_LOCATION: 通过在您的应用程序中添加它,允许您使用 WIFI 或移动蜂窝数据(或两者)来确定设备的位置。使用此权限的近似值接近城市级别。
- ACCESS_FINE_LOCATION:这会使用您的 GPS 以及 WIFI 和移动数据来获得尽可能精确的位置。通过使用它,您将获得用户的精确位置。
- ACCESS_BACKGROUND_LOCATION:这个权限是在Android 10 中引入的。所以,对于Android 10 或更高版本,如果你想在后台访问用户的位置,那么除了以上两个权限中的任何一个,你还需要添加ACCESS_BACKGROUND_LOCATION 权限。
另外,这里要注意的一件事是我们使用了危险的权限,所以我们需要明确要求用户授予权限。
因此,我们完成了先决条件,现在我们将学习如何借助示例获取当前位置。
例子
在本例中,我们将使用Fused Location API来获取更改后的位置,或者您可能会说,获取用户的当前位置。我们将使用LocationRequest
用于从FusedLocationProviderApi
.
除了获取更新的位置外,LocationRequest它还包括各种检索位置的方法,例如专业人士。其中一些方法是:
- setInterval(long millis):这用于设置您想要检查位置更新的所需时间间隔。它以毫秒为单位。
- setFastestInterval(long millis):用于设置位置更新的最快间隔。在许多情况下,这可能比您更快setInterval(long),因为如果设备上的其他应用程序以小于您的时间间隔触发位置更新,那么它将使用该更新。
- setSmallestDisplacement(float minimumDisplacementMeters):这将设置位置更新之间的最小位移,即位置更新所需的最小位移。它以米为单位,默认值为 0。
- setPriority(int priority):用于设置接收到的位置的优先级。可以是PRIORITY_BALANCED_POWER_ACCURACY(达到街区级别的准确性),也可以是PRIORITY_HIGH_ACCURACY(获得最准确的结果),也可以是PRIORITY_LOW_POWER(获得城市级别的准确性),也可以是PRIORITY_NO_POWER(在不提供的情况下获得最准确的信息)一些额外的力量)。
现在,按照以下步骤使用 Fused Location Provider 获取您的当前位置:
创建项目
- 启动一个新的 Android Studio 项目
- 选择空活动和下一步
- 名称:Fused-Location-API-Example
- 包名:com.mindorks.example.fusedlocation
- 语言:kotlin
- 结束
- 您的起始项目现已准备就绪
添加依赖项
为了使用 Fused Location API,您需要添加 location 的依赖。因此,在您的应用程序级build.gradle文件中,添加以下依赖项:
dependencies {
...
implementation 'com.google.android.gms:play-services-location:17.0.0'
}
同步项目。
添加权限
要使用位置服务,您需要在AndroidManifest.xml
文件中添加位置权限。您可以使用ACCESS_COARSE_LOCATION
或ACCESS_FINE_LOCATION
,根据您的使用情况:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
制作布局文件
在这个项目中,我们将有两个 TextView,一个用于纬度,一个用于经度。用户的当前位置将显示在这些 TextView 中。因此,该activity_main.xml
文件的代码将是:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:orientation="vertical">
<TextView
android:id="@+id/latTextView"
android:layout_width="match_parent"
android:layout_height="60sp"
android:text="@string/default_lat"
android:gravity="center"
android:layout_marginBottom="8dp"
android:textColor="@color/colorBlack"/>
<TextView
android:id="@+id/lngTextView"
android:layout_width="match_parent"
android:layout_height="60sp"
android:text="@string/default_lng"
android:gravity="center"
android:layout_marginBottom="8dp"
android:textColor="@color/colorBlack"/>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
现在,我们完成了所有依赖项和布局部分。
获得用户的许可
由于我们使用了危险的位置权限,所以我们需要明确请求权限。另外,在获取用户当前位置之前,可能会出现以下情况:
我们需要为所有这些权限检查编写函数。因此,在根目录中创建一个包并在该包中创建一个对象类。
- 包名:com.mindorks.example.fusedlocation.utils
- 对象类名:PermissionUtils
在文件中添加以下代码PermissionUtils.kt
:
object PermissionUtils {
/**
* Function to request permission from the user
*/
fun requestAccessFineLocationPermission(activity: AppCompatActivity, requestId: Int) {
ActivityCompat.requestPermissions(
activity,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
requestId
)
}
/**
* Function to check if the location permissions are granted or not
*/
fun isAccessFineLocationGranted(context: Context): Boolean {
return ContextCompat
.checkSelfPermission(
context,
Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED
}
/**
* Function to check if location of the device is enabled or not
*/
fun isLocationEnabled(context: Context): Boolean {
val locationManager: LocationManager =
context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
|| locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
}
/**
* Function to show the "enable GPS" Dialog box
*/
fun showGPSNotEnabledDialog(context: Context) {
AlertDialog.Builder(context)
.setTitle(context.getString(R.string.enable_gps))
.setMessage(context.getString(R.string.required_for_this_app))
.setCancelable(false)
.setPositiveButton(context.getString(R.string.enable_now)) { _, _ ->
context.startActivity(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS))
}
.show()
}
}
MainActivity.kt
为文件编写代码
现在,在 MainActivity.kt
文件中,重写该onStart()方法并使用该类检查是否授予PermissionUtils
了权限,以及是否授予了权限并在设备中启用了 GPS,然后调用setUpLocationListener()
负责获取当前位置的函数. 以下是 的代码onStart():
override fun onStart() {
super.onStart()
when {
PermissionUtils.isAccessFineLocationGranted(this) -> {
when {
PermissionUtils.isLocationEnabled(this) -> {
setUpLocationListener()
}
else -> {
PermissionUtils.showGPSNotEnabledDialog(this)
}
}
}
else -> {
PermissionUtils.requestAccessFineLocationPermission(
this,
LOCATION_PERMISSION_REQUEST_CODE
)
}
}
}
现在,创建一个名为setUpLocationListener().
在函数中,创建Fused Location Provider
客户端的实例。
private fun setUpLocationListener() {
val fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
}
现在,我们需要定义我们想要的位置请求类型,即我们可以设置所需的位置准确度、所需的位置更新间隔、所需的优先级等。所有这些设置都可以通过使用LocationRequest数据对象来完成。因此,我们可以添加以下代码:
// for getting the current location update after every 2 seconds with high accuracy
val locationRequest = LocationRequest().setInterval(2000).setFastestInterval(2000)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
现在,我们需要做的就是调用该
requestLocationUpdates()方法并传递LocationRequest
和 aLocationCallback.
之后,将调用 onLocationResult
并且它包含一个位置列表。您可以从此位置变量获取纬度和经度,并根据您的选择使用它。在这里,我们用这个纬度和经度更新我们的 TextView。所以,最终的代码setUpLocationListener()
将是:
private fun setUpLocationListener() {
val fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
// for getting the current location update after every 2 seconds with high accuracy
val locationRequest = LocationRequest().setInterval(2000).setFastestInterval(2000)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
fusedLocationProviderClient.requestLocationUpdates(
locationRequest,
object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult) {
super.onLocationResult(locationResult)
for (location in locationResult.locations) {
latTextView.text = location.latitude.toString()
lngTextView.text = location.longitude.toString()
}
// Few more things we can do here:
// For example: Update the location of user on server
}
},
Looper.myLooper()
)
}
最后,为请求权限的结果添加回调:
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when (requestCode) {
LOCATION_PERMISSION_REQUEST_CODE -> {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
when {
PermissionUtils.isLocationEnabled(this) -> {
setUpLocationListener()
}
else -> {
PermissionUtils.showGPSNotEnabledDialog(this)
}
}
} else {
Toast.makeText(
this,
getString(R.string.location_permission_not_granted),
Toast.LENGTH_LONG
).show()
}
}
}
}
运行应用程序
在您的设备上运行该应用程序并尝试验证所有许可情况,并尝试更改您设备的位置以查看该位置是否在 TextView 上更新。
概括
在这篇文章中,我们学习了如何在您的应用中显示用户更改的位置。我们出于同样的目的使用了 Fused Location API。