The simplest way to get the user's current location on Android using Kotlin?

Kotlin Apps/ApplicationsMobile Development

This example demonstrates how to get the user's current location on Android using Kotlin.

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

Add the following dependency in Gradle

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

Step 2 − Add the following code to 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>

Step 3 − Add the following code to 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)
   }
}

Step 4 − Create a new Kotlin class GetAddressFromIntentService.kt and add the following code

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"
   }
}

Step 5 − Add the following code to 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>

Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon Play from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen.

Click here to download the project code.

raja
Published on 26-Sep-2020 15:32:45
Advertisements