परिचय
यह उदाहरण दर्शाता है कि Kotlin का उपयोग करके एंड्रॉइड में Geocoder का उपयोग करके लैटीट्यूड और लॉन्गिट्यूड से पूरा एड्रेस कैसे प्राप्त किया जाए।
चरण 1: नया प्रोजेक्ट बनाएं
Android Studio खोलें, File → New Project पर जाएं और नया प्रोजेक्ट बनाने के लिए सभी आवश्यक विवरण भरें।
चरण 2: लेआउट XML कॉन्फ़िगर करें
res/layout/activity_main.xml में निम्नलिखित कोड जोड़ें:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16sp"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="Tutorials Point"
android:textAlignment="center"
android:textColor="@android:color/holo_green_dark"
android:textSize="32sp"
android:textStyle="bold" />
<Button
android:id="@+id/btnShowAddress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="एड्रेस दिखाएं" />
<TextView
android:id="@+id/tvAddress"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/btnShowAddress"
android:layout_centerInParent="true"
android:textColor="@android:color/background_dark"
android:textSize="12sp"
android:textStyle="bold" />
</RelativeLayout>
चरण 3: MainActivity कोड
src/MainActivity.kt में निम्नलिखित कोड जोड़ें:
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationManager
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.provider.Settings
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import android.Manifest
class MainActivity : AppCompatActivity() {
private lateinit var btnShowAddress: Button
private lateinit var tvAddress: TextView
private lateinit var location: Location
private lateinit var appLocationService: AppLocationService
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
tvAddress = findViewById(R.id.tvAddress)
appLocationService = AppLocationService(this)
btnShowAddress = findViewById(R.id.btnShowAddress)
// लोकेशन परमिशन चेक करें
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 1)
}
btnShowAddress.setOnClickListener {
location = appLocationService.getLocation(LocationManager.GPS_PROVIDER)!!
val latitude = 13.1000727
val longitude = 80.2126274
val locationAddress = LocationAddress()
locationAddress.getAddressFromLocation(
latitude, longitude, applicationContext, GeoCodeHandler()
)
showSettingsAlert()
}
}
private fun showSettingsAlert() {
AlertDialog.Builder(this).apply {
setTitle("सेटिंग्स")
setMessage("लोकेशन प्रोवाइडर सक्षम करें! सेटिंग्स मेनू पर जाएं?")
setPositiveButton("सेटिंग्स") { _, _ ->
val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
startActivity(intent)
}
setNegativeButton("रद्द") { dialog, _ -> dialog.cancel() }
show()
}
}
inner class GeoCodeHandler : Handler() {
override fun handleMessage(message: Message) {
val locationAddress = when (message.what) {
1 -> {
val bundle = message.data
bundle.getString("address") ?: ""
}
else -> ""
}
tvAddress.text = locationAddress
}
}
override fun onRequestPermissionsResult(
requestCode: Int, permissions: Array<out String>, grantResults: IntArray
) {
when (requestCode) {
1 -> {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "परमिशन प्रदान की गई", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "परमिशन अस्वीकृत", Toast.LENGTH_SHORT).show()
}
}
}
}
}
चरण 4: AppLocationService क्लास
AppLocationService.kt नाम से एक नई Kotlin क्लास बनाएं:
import android.annotation.SuppressLint
import android.app.Service
import android.content.Context
import android.content.Intent
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.os.IBinder
open class AppLocationService(context: Context) : Service(), LocationListener {
private var locationManager: LocationManager? =
context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
private lateinit var location: Location
companion object {
private const val MIN_DISTANCE_FOR_UPDATE: Long = 10
private const val MIN_TIME_FOR_UPDATE = 1000 * 60 * 2L
}
@SuppressLint("MissingPermission")
fun getLocation(provider: String?): Location? {
if (locationManager!!.isProviderEnabled(provider)) {
locationManager!!.requestLocationUpdates(
provider, MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE.toFloat(), this
)
if (locationManager != null) {
location = locationManager!!.getLastKnownLocation(provider)
return location
}
}
return null
}
override fun onLocationChanged(location: Location) {}
override fun onProviderDisabled(provider: String) {}
override fun onProviderEnabled(provider: String) {}
override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {}
override fun onBind(arg0: Intent): IBinder? = null
}
चरण 5: LocationAddress क्लास
LocationAddress.kt नाम से एक नई Kotlin क्लास बनाएं:
import android.content.Context
import android.location.Geocoder
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.Log
import java.io.IOException
import java.util.Locale
class LocationAddress {
private val tag = "LocationAddress"
fun getAddressFromLocation(
latitude: Double, longitude: Double, context: Context, handler: Handler
) {
Thread {
val geoCoder = Geocoder(context, Locale.getDefault())
var result: String = ""
try {
val addressList = geoCoder.getFromLocation(latitude, longitude, 1)
if (addressList != null && addressList.size > 0) {
val address = addressList[0]
val sb = StringBuilder()
for (i in 0 until address.maxAddressLineIndex) {
sb.append(address.getAddressLine(i)).append("\n")
}
sb.append(address.locality).append("\n")
sb.append(address.postalCode).append("\n")
sb.append(address.countryName)
result = sb.toString()
}
} catch (e: IOException) {
Log.e(tag, "GeoCoder से कनेक्ट करने में असमर्थ", e)
} finally {
val message = Message.obtain()
message.target = handler
message.what = 1
val bundle = Bundle()
result = "लैटीट्यूड: $latitude लॉन्गिट्यूड: $longitude\n\nएड्रेस:\n$result"
bundle.putString("address", result)
message.data = bundle
message.sendToTarget()
}
}.start()
}
}
चरण 6: मैनिफेस्ट कॉन्फ़िगर करें
androidManifest.xml में निम्नलिखित कोड जोड़ें:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="app.com.q11">
<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 Studio में प्रोजेक्ट की एक्टिविटी फाइल खोलें और टूलबार से Run आइकन पर क्लिक करें। अपना मोबाइल डिवाइस चुनें और ऐप का डिफॉल्ट स्क्रीन देखें।
महत्वपूर्ण नोट्स
- Geocoder के लिए इंटरनेट कनेक्शन आवश्यक है
- एंड्रॉइड 6+ पर रनटाइम परमिशन अनिवार्य है
- उत्पादन ऐप्स के लिए FusedLocationProviderClient का उपयोग करने की सिफारिश की जाती है