如何使用 Kotlin 在 Android 设备上跟踪当前位置(纬度和经度)?\n


此示例演示了如何使用 Kotlin 在 Android 设备上跟踪当前位置(纬度和经度)。

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

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

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:id="@+id/linearLayout"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:gravity="center"
   android:orientation="vertical"
   tools:context=".MainActivity">
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginStart="10dp"
      android:text="Current Location in Latitude and Longitude:"
      android:textAlignment="center"
      android:textColor="@color/common_google_signin_btn_text_dark_focused"
      android:textIsSelectable="true"
      android:textSize="24sp"
      android:textStyle="bold" />
   <TextView
      android:id="@+id/latitudeText"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginStart="10dp"
      android:textColor="@color/common_google_signin_btn_text_dark_focused"
      android:textIsSelectable="true"
      android:textSize="24sp"
      android:textStyle="bold" />
   <TextView
      android:id="@+id/longitudeText"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginStart="10dp"
      android:layout_marginTop="20dp"
      android:textColor="@color/common_google_signin_btn_text_dark_focused"
      android:textIsSelectable="true"
      android:textSize="24sp"
      android:textStyle="bold" />
</LinearLayout>

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

package app.com.kotlipapp
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Location
import android.net.Uri
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.core.app.ActivityCompat
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
class MainActivity : AppCompatActivity() {
   private var fusedLocationClient: FusedLocationProviderClient? = null
   private var lastLocation: Location? = null
   private var latitudeLabel: String? = null
   private var longitudeLabel: String? = null
   private var latitudeText: TextView? = null
   private var longitudeText: TextView? = null
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      latitudeLabel = resources.getString(R.string.latitudeBabel)
      longitudeLabel = resources.getString(R.string.longitudeBabel)
      latitudeText = findViewById<View>(R.id.latitudeText) as TextView
      longitudeText = findViewById<View>(R.id.longitudeText) as TextView
      fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
   }
   public override fun onStart() {
      super.onStart()
      if (!checkPermissions()) {
         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions()
         }
      }
      else {
         getLastLocation()
      }
   }
   private fun getLastLocation() {
      fusedLocationClient?.lastLocation!!.addOnCompleteListener(this) { task ->
         if (task.isSuccessful && task.result != null) {
            lastLocation = task.result
            latitudeText!!.text = latitudeLabel + ": " + (lastLocation)!!.latitude
            longitudeText!!.text = longitudeLabel + ": " + (lastLocation)!!.longitude
         }
         else {
            Log.w(TAG, "getLastLocation:exception", task.exception)
            showMessage("No location detected. Make sure location is enabled on the device.")
         }
      }
   }
   private fun showMessage(string: String) {
      val container = findViewById<View>(R.id.linearLayout)
      if (container != null) {
         Toast.makeText(this@MainActivity, string, Toast.LENGTH_LONG).show()
      }
   }
   private fun showSnackbar(
      mainTextStringId: String, actionStringId: String,
      listener: View.OnClickListener
   ) {
      Toast.makeText(this@MainActivity, mainTextStringId, Toast.LENGTH_LONG).show()
   }
   private fun checkPermissions(): Boolean {
      val permissionState = ActivityCompat.checkSelfPermission(
      this,
      Manifest.permission.ACCESS_COARSE_LOCATION
   )
   return permissionState == PackageManager.PERMISSION_GRANTED
}
private fun startLocationPermissionRequest() {
   ActivityCompat.requestPermissions(
      this@MainActivity,
      arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION),
      REQUEST_PERMISSIONS_REQUEST_CODE
   )
}
private fun requestPermissions() {
   val shouldProvideRationale = ActivityCompat.shouldShowRequestPermissionRationale(
      this,
      Manifest.permission.ACCESS_COARSE_LOCATION
   )
   if (shouldProvideRationale) {
      Log.i(TAG, "Displaying permission rationale to provide additional context.")
      showSnackbar("Location permission is needed for core functionality", "Okay",
      View.OnClickListener {
         startLocationPermissionRequest()
      })
   }
   else {
      Log.i(TAG, "Requesting permission")
      startLocationPermissionRequest()
   }
}
override fun onRequestPermissionsResult(
   requestCode: Int, permissions: Array<String>,
   grantResults: IntArray
) {
   Log.i(TAG, "onRequestPermissionResult")
   if (requestCode == REQUEST_PERMISSIONS_REQUEST_CODE) {
      when {
         grantResults.isEmpty() -> {
            // If user interaction was interrupted, the permission request is cancelled and you
            // receive empty arrays.
            Log.i(TAG, "User interaction was cancelled.")
         }
         grantResults[0] == PackageManager.PERMISSION_GRANTED -> {
            // Permission granted.
            getLastLocation()
         }
         else -> {
            showSnackbar("Permission was denied", "Settings",
               View.OnClickListener {
                  // Build intent that displays the App settings screen.
                  val intent = Intent()
                  intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                  val uri = Uri.fromParts(
                     "package",
                     Build.DISPLAY, null
                  )
                  intent.data = uri
                  intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                  startActivity(intent)
                  }
               )
            }
         }
      }
   }
   companion object {
      private val TAG = "LocationProvider"
      private val REQUEST_PERMISSIONS_REQUEST_CODE = 34
   }
}

步骤 4 - 将以下代码添加到 res/strings.xml 中。

<resources>
   <string name="app_name">KotlipApp</string>
   <string name="latitudeBabel">Latitude</string>
   <string name="longitudeBabel">Longitude</string>
</resources>

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

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="app.com.kotlipapp">
   <uses-permission android:name="android.permission.INTERNET"/>
   <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
   <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年4月20日

2K+ 次查看

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告