Skip to content

Instantly share code, notes, and snippets.

@NaikSoftware
Created January 22, 2019 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NaikSoftware/499938941504a49654de47dbdd1e8f74 to your computer and use it in GitHub Desktop.
Save NaikSoftware/499938941504a49654de47dbdd1e8f74 to your computer and use it in GitHub Desktop.
Android: Retrieve city from current device location
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ua.naiksoftware.citynametester">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application android:allowBackup="true"
android:label="@string/app_name"
android:icon="@mipmap/ic_launcher"
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"/>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.location.Geocoder
import android.location.LocationManager
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import java.io.IOException
import java.util.*
import android.content.Intent
import android.provider.Settings
class MainActivity : AppCompatActivity() {
companion object {
const val RC_PERMISSION_LOCATION = 1234
}
lateinit var textView: TextView
lateinit var locationManager: LocationManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
textView = findViewById(R.id.text)
locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
}
override fun onStart() {
super.onStart()
requestLocationPermissions()
}
private fun requestLocationPermissions() {
if (!checkLocationEnabled()) return
if (ContextCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
AlertDialog.Builder(this)
.setMessage(R.string.location_request_reason)
.setNegativeButton(R.string.cancel, null)
.setPositiveButton(R.string.ok) { _, _ ->
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
RC_PERMISSION_LOCATION
)
}
.show()
} else {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
RC_PERMISSION_LOCATION
)
}
} else {
retrieveSuggestions()
}
}
private fun checkLocationEnabled(): Boolean {
var gpsEnabled = false
var networkEnabled = false
try {
gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
} catch (ex: Exception) {
}
try {
networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
} catch (ex: Exception) {
}
if (!gpsEnabled && !networkEnabled) {
AlertDialog.Builder(this)
.setMessage(getString(R.string.enable_location_message))
.setPositiveButton(R.string.ok) {_, _ ->
startActivity(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS))
}
.setNegativeButton(R.string.cancel, null).show()
return false
}
return true
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
if (requestCode == RC_PERMISSION_LOCATION) {
if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
retrieveSuggestions()
} else {
textView.setText(R.string.location_permissions_denied)
}
}
}
private fun retrieveSuggestions() {
val location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)
if (location == null) {
textView.setText(R.string.last_location_empty_message)
} else {
retrieveCityName(location.latitude, location.longitude)
}
}
private fun retrieveCityName(lat: Double, lng: Double) {
val geoCoder = Geocoder(this, Locale.getDefault())
val text = StringBuilder()
try {
val addresses = geoCoder.getFromLocation(lat, lng, 1)
if (addresses != null) {
text.append(addresses[0].locality)
} else {
text.append("No Address returned!")
}
} catch (e: IOException) {
e.printStackTrace()
text.append("Can not get address! " + e.toString())
}
textView.text = text.toString()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment