Get current location android kotlin

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

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.

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, 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("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? = 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 = """ $$ Locality: $ County: $ State: $ Country: $ Postal Code: $ """.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

Читайте также:  Строковое представление числа java

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 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.

Источник

Getting Current Location in Android using Kotlin

Current Location in Android using Kotlin

The fused location provider retrieves the device’s last known location. The fused location provider is one of the location APIs in Google Play services.

It manages the underlying location technology and provides a simple API so that you can specify requirements at a high level, like high accuracy or low power.

Add dependency in build.gradle file of you app.

Ask for Location permission from User. Since Location is a dangerous Permission for android so we need to ask the user to grant permission for it.

Android offers two location permissions:

The permission you choose determines the accuracy of the location returned by the API.

Add these two permission in you manifest file.

As you may know that from Android 6.0 (Marshmallow) you must request permissions for important access in the runtime. Cause it’s a security issue where while installing an application, the user may not clearly understand about important permission of their device.

As we need the location information of the user so we’ll need to implement the permission request also in runtime.

These will be in further Steps

checkPermissions()

This method will tell us whether or not the user grant us to access ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION.

private fun checkPermissions(): Boolean < if ( ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission (this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)< return true >return false >

onRequestPermissionsResult()

This method is called when a user Allow or Deny our requested permissions. So it will help us to move forward if the permissions are granted.

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) < if (requestCode == PERMISSION_ID) < if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) < // Granted. Start getting the location information >> >

isLocationEnabled()

This will check if the user has turned on location from the setting, Cause user may grant the app to user location but if the location setting is off then it’ll be of no use.

private fun isLocationEnabled(): Boolean

You may notice that while requesting for permission and in after the permission result, we used PERMISSION_ID, it’s a interger value which helps us to identify user’s action with which permission request. You can provide any unique value here.

Now time to write the MainActivity.kt

package com.jayant.mylocation import android.Manifest import android.content.Context import android.content.pm.PackageManager import android.location.LocationManager import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.core.app.ActivityCompat class MainActivity : AppCompatActivity() < val PERMISSION_ID = 42 override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) >private fun isLocationEnabled(): Boolean < var locationManager: LocationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled( LocationManager.NETWORK_PROVIDER ) >private fun checkPermissions(): Boolean < if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)< return true >return false > private fun requestPermissions() < ActivityCompat.requestPermissions( this, arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION), PERMISSION_ID ) >override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) < if (requestCode == PERMISSION_ID) < if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) < // Granted. Start getting the location information >> > >

Now we’ll use the actual Fused Location Provider API to get the user’s current position. For this, you should declare a variable first lateint var using mFusedLocationClient: FusedLocationClient

Then we’ll create a method named getLastLocation() which will use to API and return the last recorder location information of the device. Also this method will check first if our permission is granted or not and if the location setting is turned on.

@SuppressLint("MissingPermission") private fun getLastLocation() < if (checkPermissions()) < if (isLocationEnabled()) < mFusedLocationClient.lastLocation.addOnCompleteListener(this) < task ->var location: Location? = task.result if (location == null) < requestNewLocationData() >else < findViewById(R.id.latTextView).text = location.latitude.toString() findViewById(R.id.lonTextView).text = location.longitude.toString() > > > else < Toast.makeText(this, "Turn on location", Toast.LENGTH_LONG).show() val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS) startActivity(intent) >> else < requestPermissions() >>

As you can see first it’ll check if we have granted permissions or not using our created method checkPermission() and if not, it’ll request for location permission. Then it’ll check if the location setting is turned on or off. If turned off, will open the location setting using intent to turn it on.

If every requirment is good then it’ll look for the last recorded location information and put the latitude and longitude values in our TextView using

latTextView.text = location.latitude.toString() lonTextView.text =location.longitude.toString()

STEP – 8 (optional)

But here’s a thing you must know, for some rare cases the location can be null like:

  • In some device, if you turn off the location and again turn on, the previous recorded location information will be cleared.
  • May the user never turned on location before using your App, this time previous location information will be null too.

To avoid these rare cases when the location == null, we called a new method requestNewLocation() which will record the location information in runtime.

@SuppressLint("MissingPermission") private fun requestNewLocationData()

This method will make a new location request with highest accuracy.

When an update receives it’ll call a callBack method named mLocationCallback.

private val mLocationCallback = object : LocationCallback() < override fun onLocationResult(locationResult: LocationResult) < var mLastLocation: Location = locationResult.lastLocation findViewById(R.id.latTextView).text = mLastLocation.latitude.toString() findViewById(R.id.lonTextView).text = mLastLocation.longitude.toString() > >

So when we get the location update, we set the latitude and longitude values in our TextViews.

So finally we’ll call our getLastLocation() method in our onCreate() method and also when user grants the permission request.

Final MainActivity.kt

package com.jayant.mylocation import android.Manifest import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.location.Location import android.location.LocationManager import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Looper import android.provider.Settings import android.widget.TextView import android.widget.Toast import androidx.core.app.ActivityCompat import com.google.android.gms.location.* class MainActivity : AppCompatActivity() < val PERMISSION_ID = 42 lateinit var mFusedLocationClient: FusedLocationProviderClient override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this) getLastLocation() >@SuppressLint("MissingPermission") private fun getLastLocation() < if (checkPermissions()) < if (isLocationEnabled()) < mFusedLocationClient.lastLocation.addOnCompleteListener(this) < task ->var location: Location? = task.result if (location == null) < requestNewLocationData() >else < findViewById(R.id.latTextView).text = location.latitude.toString() findViewById(R.id.lonTextView).text = location.longitude.toString() > > > else < Toast.makeText(this, "Turn on location", Toast.LENGTH_LONG).show() val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS) startActivity(intent) >> else < requestPermissions() >> @SuppressLint("MissingPermission") private fun requestNewLocationData() < var mLocationRequest = LocationRequest() mLocationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY mLocationRequest.interval = 0 mLocationRequest.fastestInterval = 0 mLocationRequest.numUpdates = 1 mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this) mFusedLocationClient. requestLocationUpdates( mLocationRequest, mLocationCallback, Looper.myLooper() ) >private val mLocationCallback = object : LocationCallback() < override fun onLocationResult(locationResult: LocationResult) < var mLastLocation: Location = locationResult.lastLocation findViewById(R.id.latTextView).text = mLastLocation.latitude.toString() findViewById(R.id.lonTextView).text = mLastLocation.longitude.toString() > > private fun isLocationEnabled(): Boolean < var locationManager: LocationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled( LocationManager.NETWORK_PROVIDER ) >private fun checkPermissions(): Boolean < if (ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_COARSE_LOCATION ) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_FINE_LOCATION ) == PackageManager.PERMISSION_GRANTED ) < return true >return false > private fun requestPermissions() < ActivityCompat.requestPermissions( this, arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION), PERMISSION_ID ) >override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) < if (requestCode == PERMISSION_ID) < if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) < getLastLocation() >> > >

Источник

Get Current Location in Android Studio using Kotlin

Sometimes, we need to add the current location of the users to the project, that’s why we are creating this small project for you. Hello coders, welcome to Techpass Master, In this post, we’re going to learn, How to Get Current Location in Android Studio using Kotlin programming language. This project will help you to get the current location of the users, so without any further discussion let’s start building the project 🙂

Get Current Location in Android Studio using Kotlin

Get Current Location in Android Studio using Kotlin (Thumbnail)

First, you have to need to create a project to get your current location, below are the steps you can follow step by step.

Step 1: Create A Project For Real time location

  • Start a new Android Studio Project.
  • Select empty Activity and click Next.
  • Project Name: RealTimeLocation.
  • Choose Language: Kotlin.
  • Now click Finish.
  • Your project is ready now.

After building the project, you will see your project is ready to start building an app.:

Step 2: Enable View Binding

Step 3: Add Permission

Go to your android studio project. Open AndroidManifest.xml and add INTERNET permission for network requests and LOCATION permission for the location.

Now we are going to design a layout for showing the current latitude, longitude, Country Name, Locality, and Address.

Step 4: Open Main XML Layout and Write UI Code

Now open activity_main.xml and add the below code. In this layout, we’ll design the UI of the Real time location App.

After adding the above (XML) code, let’s write the logic to get the real-time location.

Step 5: Open Main Activity and Write Logic for Location

First, we will bind the layout to the activity.

private lateinit var mainBinding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?)

After binding the layout, we have to initialize the location services for the location, for that just you have to create a variable (mFusedLocationClient).

private lateinit var mFusedLocationClient: FusedLocationProviderClient Now initialize the location service. override fun onCreate(savedInstanceState: Bundle?)

Now, we will check whether the location is enabled or not for that we have to create a function- isLocationEnabled(). This function will be responsible to check whether the location is enabled or not and it will return the true/false value.

private fun isLocationEnabled(): Boolean

Now, we have to create the function and override the function for checking the permission.

private fun checkPermissions(): Boolean < if (ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_COARSE_LOCATION ) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_FINE_LOCATION ) == PackageManager.PERMISSION_GRANTED ) < return true >return false > private fun requestPermissions() < ActivityCompat.requestPermissions( this, arrayOf( Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION ), permissionId ) >@SuppressLint("MissingSuperCall") override fun onRequestPermissionsResult( requestCode: Int, permissions: Array, grantResults: IntArray ) < if (requestCode == permissionId) < if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) < getLocation() >> >

After checking the permission, we’ve to create one more function (getLocation()) which will be responsible to check permission and location, if permission is not granted then it will request you to grant the permission.

@SuppressLint("MissingPermission", "SetTextI18n") private fun getLocation() < if (checkPermissions()) < if (isLocationEnabled()) < mFusedLocationClient.lastLocation.addOnCompleteListener(this) < task ->val location: Location? = task.result if (location != null) < val geocoder = Geocoder(this, Locale.getDefault()) val list: List= geocoder.getFromLocation(location.latitude, location.longitude, 1) mainBinding.apply < tvLatitude.text = "Latitude\n$" tvLongitude.text = "Longitude\n$" tvCountryName.text = "Country Name\n$" tvLocality.text = "Locality\n$" tvAddress.text = "Address\n$" > > > > else < Toast.makeText(this, "Please turn on location", Toast.LENGTH_LONG).show() val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS) startActivity(intent) >> else < requestPermissions() >>

After creating the all thing, we have to need to perform a click listener, this listener is responsible for to call getCurrent() function.

override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) mainBinding = ActivityMainBinding.inflate(layoutInflater) setContentView(mainBinding.root) mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this) this listner is responsoble to call getCurrent fuction // mainBinding.btnLocation.setOnClickListener < getLocation() >>

Complete code of the Get current location.

Get Current Location in Android Studio using Kotlin (final App result

Recommended Reading:

I hope you liked the post. If you have any questions regarding this post. Feel free to comment and share the post with your friends.

Happy Learning.

Источник

Оцените статью