How to get user location in Android


Many apps and Android use a location like ordering cabs or delivering food and others. A simple Android application would return the user's latitude and longitude. When passing latitude and longitude in Google map API then gives full information like city name, country name, etc.

Below following query 

https://www.google.com/maps/search/?api=1&query=,

Let’s take the example of getting the current location and setting in to textview


Here is the step by step Implementation process:

 Step 1 : set permissions on mobile application
Mobile permission was started by Android 6.0 (Marshmallow), the concept of run-time permission was rolled in and so the same will be used.
 
Below permission required
  1. <uses-permission android=”android.permission.ACCESS_COARSE_LOCATION”/>
  2. <uses-permission android=”andorid.permission.ACCESS_FINE_LOCATION”/>

We need to add all these permissions in the androidmanifest.xml.

 app>manifests->Androidmanifest.xml

  After adding all the permissions, AndroidManifest.xml file looks like:
 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.MyApplication"
tools:targetApi="31">
<activity
android:name=".MainActivityone"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Step 2 : Enable View Binding
 buildFeatures{
viewBinding=true
 }
Step 3 : Open Main XML Layout and Write UI Code.

Now open activity_main.xml and add the following code, in this layout, we will design the UI of the Real-time location app.

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

<ImageView
android:id="@+id/imageView2"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_marginTop="20dp"
android:src="@drawable/company_logo"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<TextView
android:id="@+id/tvTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:gravity="center"
android:text="Current Location"
android:textColor="#651FFF"
android:textSize="28sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/imageView2" />

<TextView
android:id="@+id/tv_latitude"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="28dp"
android:layout_marginStart="20dp"
android:text="Latitude"
android:textColor="@color/black"
android:textSize="16sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tvTitle" />

<TextView
android:id="@+id/tv_longitude"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="16dp"
android:text="Longitude"
android:textColor="@color/black"
android:textSize="16sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tv_latitude" />

<TextView
android:id="@+id/tv_countryName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:layout_marginStart="20dp"
android:text="Country Name"
android:textColor="@color/black"
android:textSize="16sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tv_longitude" />

<TextView
android:id="@+id/tv_Locality"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Locality"
android:layout_marginStart="20dp"
android:textColor="@color/black"
android:textSize="16sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tv_countryName" />

<TextView
android:id="@+id/tv_address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Address"
android:layout_marginStart="20dp"
andEnable View Bindingroid:textColor="@color/black"
android:textSize="16sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tv_Locality" />

<Button
android:id="@+id/btn_location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get My Current Location"
android:textAllCaps="false"
android:textSize="16sp"
android:background="@color/cardview_dark_background"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginBottom="16dp"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

 

Step 4 : Open Main Activity and Write Logic for Location
 import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Address
import android.location.Geocoder
import android.location.Location
import android.location.LocationManager
import android.os.Bundle
import android.provider.Settings
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
import com.velodate.myapplication.databinding.ActivityMainActivityoneBinding
import java.util.*

class MainActivityone : AppCompatActivity() {
private lateinit var mainBinding: ActivityMainActivityoneBinding
private lateinit var mFusedLocationClient: FusedLocationProviderClient
private val permissionId = 2
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mainBinding = ActivityMainActivityoneBinding.inflate(layoutInflater)
setContentView(mainBinding.root)
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
mainBinding.btnLocation.setOnClickListener {
getLocation()
}
}
@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: MutableList<Address>? =
geocoder.getFromLocation(location.latitude, location.longitude, 1)
mainBinding.apply {
tvLatitude.text = "Latitude - ${list?.get(0)?.latitude}"
tvLongitude.text = "Longitude - ${list?.get(0)?.longitude}"
tvCountryName.text = "Country Name -${list?.get(0)?.countryName}"
tvLocality.text = "Locality - ${list?.get(0)?.locality}"
tvAddress.text = "Address - ${list?.get(0)?.getAddressLine(0)}"
}
}
}
} else {
Toast.makeText(this, "Please turn on location", Toast.LENGTH_LONG).show()
val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
startActivity(intent)
}
} else {
requestPermissions()
}
}
private fun isLocationEnabled(): Boolean {
val 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
),
permissionId
)
}
@SuppressLint("MissingSuperCall")
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
if (requestCode == permissionId) {
if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
getLocation()
}
}
}
}

 

Step 5 :Output of above example 


Happy coding!



365Bloggy May 27, 2024
Share this post
Tags
SUBSCRIBE THIS FORM


Archive