Skip to content

Instantly share code, notes, and snippets.

@suchoX
Created February 20, 2018 06:13
Show Gist options
  • Save suchoX/5907a7d1df744e0e6f7b7913b583915a to your computer and use it in GitHub Desktop.
Save suchoX/5907a7d1df744e0e6f7b7913b583915a to your computer and use it in GitHub Desktop.
package com.crimson.jade.utils
import android.content.Context
import android.location.Geocoder
import android.location.Location
import android.location.LocationManager
import android.os.Build
import android.os.Bundle
import android.widget.Toast
import com.crimson.jade.R
import com.crimson.jade.dagger.qualifier.ApplicationContext
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.api.GoogleApiClient
import com.google.android.gms.location.LocationListener
import com.google.android.gms.location.LocationRequest
import com.google.android.gms.location.LocationServices
import timber.log.Timber
import java.util.Locale
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ServiceLocationUtils @Inject internal constructor(@ApplicationContext internal var context: Context,
internal var prefsUtils: PrefsUtils) : GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private var googleApiClient: GoogleApiClient? = null
private lateinit var locationRequest: LocationRequest
private var location: Location? = null
private var callback: LocationRequestCallback? = null
fun getLocationIfGivenPermission(callback: LocationRequestCallback) {
this.callback = callback
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
getLocation()
return
}
if (prefsUtils.getLocationPermissionRequested()) {
getLocation()
} else {
callback.onLocationChanged(-1.0, -1.0, "")
}
}
private fun getLocation() {
if (checkIfLocationEnabled()) {
googleApiClient = GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build()
googleApiClient?.connect()
locationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setNumUpdates(1)
} else {
Toast.makeText(context, R.string.location_disabled_service, Toast.LENGTH_LONG).show()
callback?.onLocationChanged(-1.0, -1.0, "")
}
}
private fun checkIfLocationEnabled(): Boolean {
val locationManager: LocationManager = context.getSystemService(
Context.LOCATION_SERVICE) as LocationManager
return locationManager.isProviderEnabled(
LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(
LocationManager.NETWORK_PROVIDER)
}
private fun getAddress(latitude: Double, longitude: Double) {
val geoCoder: Geocoder = Geocoder(context, Locale.getDefault())
val addresses = geoCoder.getFromLocation(latitude, longitude, 1)
if (addresses != null && addresses.size != 0) {
val address = addresses[0].getAddressLine(
0) // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
val city = addresses[0].locality
val state = addresses[0].adminArea
val country = addresses[0].countryName
val postalCode = addresses[0].postalCode
val finalAddress: String = generateFinalAddress(address, city)
callback?.onLocationChanged(latitude, longitude, finalAddress)
} else {
callback?.onLocationChanged(latitude, longitude, "")
}
}
private fun generateFinalAddress(address: String, city: String): String {
val startPosition = address.indexOf(',')
var finalAddress = address.substring(startPosition + 1, address.length)
finalAddress = finalAddress + ", " + city
if (finalAddress.length > 30) {
finalAddress = finalAddress.substring(0, 28)
finalAddress += "..."
}
return finalAddress
}
fun onStop() {
googleApiClient?.disconnect()
}
override fun onConnected(p0: Bundle?) {
if (googleApiClient?.isConnected ?: false) {
location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient)
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest,
this)
} else {
location?.latitude?.let {
location?.longitude?.let { it1 ->
getAddress(it, it1)
}
}
}
}
}
override fun onConnectionSuspended(p0: Int) {
}
override fun onConnectionFailed(p0: ConnectionResult) {
Timber.d("onConnectionFailed" + p0)
Toast.makeText(context, R.string.couldnt_get_location_service, Toast.LENGTH_LONG).show()
callback?.onLocationChanged(-1.0, -1.0, "")
}
override fun onLocationChanged(location: Location) {
getAddress(location.latitude, location.longitude)
}
interface LocationRequestCallback {
fun onLocationChanged(latitude: Double, longitude: Double, address: String)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment