使用 Kotlin 在 Android 上获取用户当前位置的最简单方法?


此示例演示了如何使用 Kotlin 在 Android 上获取用户当前位置。

步骤 1 − 在 Android Studio 中创建一个新项目,转到文件 ⇒ 新建项目,并填写所有必需的详细信息以创建新项目。

在 Gradle 中添加以下依赖项

implementation 'com.google.android.gms:play-services-location:17.0.0'

步骤 2 − 将以下代码添加到 res/layout/activity_main.xml 中。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:padding="4dp"
   tools:context=".MainActivity">
   <TextView
      android:id="@+id/text"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="70dp"
      android:background="#008080"
      android:padding="5dp"
      android:text="TutorialsPoint"
      android:textColor="#fff"
      android:textSize="24sp"
      android:textStyle="bold" />
   <TextView
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:layout_below="@+id/text"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="40dp"
      android:text="Get Current Location and City Name"
      android:textAlignment="center"
      android:textColor="@android:color/holo_orange_dark"
      android:textSize="24sp"
      android:textStyle="bold" />
   <TextView
      android:id="@+id/textView"
      android:textColor="@android:color/background_dark"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:textSize="16sp"
      android:textStyle="bold" />
</RelativeLayout>

步骤 3 − 将以下代码添加到 src/MainActivity.kt 中

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Geocoder
import android.location.Location
import android.os.Bundle
import android.os.Handler
import android.os.ResultReceiver
import android.util.Log
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.google.android.gms.location.*
class MainActivity : AppCompatActivity() {
   private lateinit var fusedLocationClient: FusedLocationProviderClient
   private val locationPermissionCode = 2
   private lateinit var addressResultReceiver: LocationAddressResultReceiver
   private lateinit var currentAddTv: TextView
   private lateinit var currentLocation: Location
   private lateinit var locationCallback: LocationCallback
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      addressResultReceiver = LocationAddressResultReceiver(Handler())
      currentAddTv = findViewById(R.id.textView)
      fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
      locationCallback = object : LocationCallback() {
         override fun onLocationResult(locationResult: LocationResult) {
            currentLocation = locationResult.locations[0]
            getAddress()
         }
      }
      startLocationUpdates()
   }
   private fun startLocationUpdates() {
      if ((ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
         ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
locationPermissionCode)
      }
      else {
         val locationRequest = LocationRequest()
         locationRequest.interval = 2000
         locationRequest.fastestInterval = 1000
         locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
         fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null)
      }
   }
   private fun getAddress() {
      if (!Geocoder.isPresent()) {
         Toast.makeText(this@MainActivity, "Can't find current address, ", Toast.LENGTH_SHORT).show()
return
      }
      val intent = Intent(this, GetAddressIntentService::class.java)
      intent.putExtra("add_receiver", addressResultReceiver)
      intent.putExtra("add_location", currentLocation)
      startService(intent)
   }
   override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
      if (requestCode == locationPermissionCode) {
         if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show()
            startLocationUpdates()
         }
         else {
            Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show()
         }
      }
   }
   private inner class LocationAddressResultReceiver(handler: Handler) : ResultReceiver(handler) {
      override fun onReceiveResult(resultCode: Int, resultData: Bundle) {
         if (resultCode == 0) {
            Log.d("Address", "Location null retrying")
            getAddress()
         }
         if (resultCode == 1) {
            Toast.makeText(this@MainActivity, "Address not found, ", Toast.LENGTH_SHORT).show()
         }
         val currentAdd = resultData.getString("address_result")
         if (currentAdd != null) {
            showResults(currentAdd)
         }
      }
   }
   private fun showResults(currentAdd: String) {
      currentAddTv.text = currentAdd
   }
   override fun onResume() {
      super.onResume()
      startLocationUpdates()
   }
   override fun onPause() {
      super.onPause()
      fusedLocationClient.removeLocationUpdates(locationCallback)
   }
}

步骤 4 − 创建一个新的 Kotlin 类 GetAddressFromIntentService.kt 并添加以下代码

import android.app.IntentService
import android.content.Intent
import android.location.Address
import android.location.Geocoder
import android.location.Location
import android.os.Bundle
import android.os.ResultReceiver
import android.util.Log
import java.util.*
class GetAddressIntentService : IntentService(IDENTIFIER) {
   private var addressResultReceiver: ResultReceiver? = null
   override fun onHandleIntent(intent: Intent?) {
      val msg: String
      addressResultReceiver = Objects.requireNonNull(intent)!!.getParcelableExtra("add_receiver")
      if (addressResultReceiver == null) {
         Log.e("GetAddressIntentService", "No receiver, not processing the request further")
         return
      }  
      val location = intent!!.getParcelableExtra<Location>("add_location")
      if (location == null) {
         msg = "No location, can't go further without location"
         sendResultsToReceiver(0, msg)
         return
      }
      val geoCoder = Geocoder(this, Locale.getDefault())
      var addresses: List<Address>? = null
      try {
         addresses = geoCoder.getFromLocation(location.latitude, location.longitude, 1)
      }
      catch (ioException: Exception) {
         Log.e("", "Error in getting address for the location")
      }
      if (addresses == null || addresses.isEmpty()) {
         msg = "No address found for the location"
         sendResultsToReceiver(1, msg)
      }
      else {
         val address = addresses[0]
         val addressDetails = """
         ${address.featureName}
         ${address.thoroughfare}
         Locality: ${address.locality}
         County: ${address.subAdminArea}
         State: ${address.adminArea}
         Country: ${address.countryName}
         Postal Code: ${address.postalCode}
         """.trimIndent()
         sendResultsToReceiver(2, addressDetails)
      }
   }
   private fun sendResultsToReceiver(resultCode: Int, message: String) {
      val bundle = Bundle()
      bundle.putString("address_result", message)
      addressResultReceiver!!.send(resultCode, bundle)
   }
   companion object {
      private const val IDENTIFIER = "GetAddressIntentService"
   }
}

步骤 5 − 将以下代码添加到 androidManifest.xml 中

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

让我们尝试运行您的应用程序。我假设您已将您的实际 Android 移动设备连接到您的计算机。要从 Android Studio 运行应用程序,请打开您的项目活动文件之一,然后单击工具栏中的运行图标 播放 。选择您的移动设备作为选项,然后检查您的移动设备,它将显示您的默认屏幕。

点击 这里 下载项目代码。

更新于: 2020-11-28

1K+ 浏览量

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告