Rahul Routh
Rahul Routh

Reputation: 45

FusedLocationProviderClient is not working in android 12 or lower. How to solve this

I am getting address and lat and long in android 13 and also working lower version

fusedLocationProviderClient?.lastLocation?.addOnCompleteListener(this) { task -> val location: Location? = task.result

                Log.d("SDsadsad ", "sdsdit " + location)

                if (location != null) {
                    val geocoder = Geocoder(this, Locale.getDefault())
                    var addresses: List<Address>? = null
                    try {
                        addresses =
                            geocoder.getFromLocation(location.latitude, location.longitude, 1)

                        Log.d("SDsadsad ", "sdsd " + addresses.toString())

                        langitude = addresses!![0].latitude.toString()
                        longitude = addresses!![0].longitude.toString()
                        address = addresses!![0].getAddressLine(0).toString()
                        pin = addresses!![0].postalCode.toString()

                        val telephone = this.getSystemService(TELEPHONY_SERVICE) as TelephonyManager
                        phone =  telephone.line1Number.toString()

                        val dev_id = Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID)

                        device_id = dev_id.toString()
                        brand = Build.BRAND.toString()
                        model = Build.MODEL.toString()

                        val str_dateTime = DateFormat.format("yyyy-MM-dd HH:mm:ss", Date())

                        alldataShowWaterMark = "User Name: "+Constant.USER_FULL_NAME+"\n"+
                                "Langitude: "+langitude+"\n"+
                                "Longitude: "+longitude+"\n"+
                                "Address: "+address+"\n"+
                                "PinCode: "+pin+"\n"+
                                "Phone No.: "+phone+"\n"+
                                "Device Id: "+device_id+"\n"+
                                "Brand Name: "+brand+"\n"+
                                "Model No.: "+model+"\n"+
                                "Data On Time: "+str_dateTime+"\n"

                 

                    } catch (e: IOException) {
                        e.printStackTrace()
                        Log.d("SDsadsad ", "exception " + e.toString())
                    }
                }
            }

Upvotes: 1

Views: 233

Answers (1)

Eugene P.
Eugene P.

Reputation: 1036

Here is an example of how you can get last known location from LocationActivity. It will be available from LocationActivity.lastLocation. Here I do not provide location permission handling, just extension function permissionNotGranted to check if app has necessary permissions.

import android.Manifest.permission
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.os.PersistableBundle
import android.util.Log
import androidx.core.app.ActivityCompat

class LocationActivity : Activity(), LocationListener {

    private var locationManager: LocationManager? = null

    override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
        super.onCreate(savedInstanceState, persistentState)
        initLocationManager()
    }

    override fun onDestroy() {
        if (locationManager != null) locationManager?.removeUpdates(this)
        super.onDestroy()
    }

    private fun initLocationManager() {
        if (this.permissionNotGranted(permission.ACCESS_COARSE_LOCATION) ||
            this.permissionNotGranted(permission.ACCESS_FINE_LOCATION)
        ) return
        try {
            val minute = (60 * 1000).toLong()
            locationManager = getSystemService(LocationManager::class.java)
            if (locationManager?.isProviderEnabled(LocationManager.GPS_PROVIDER) == true)
                locationManager?.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER,
                    minute,
                    0f,
                    this
                )
            try {
                if (locationManager?.isProviderEnabled(LocationManager.NETWORK_PROVIDER) == true)
                    locationManager?.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        minute,
                        0f,
                        this
                    )
            } catch (exception: IllegalArgumentException) {
                Log.e("activate NETWORK_PROVIDER exception ", exception.localizedMessage)
            }
        } catch (exception: SecurityException) {
            Log.e("initLocationManager exception", exception.localizedMessage)
        }
    }

    override fun onLocationChanged(location: Location) {
        val bestLocation = getBestLocation(location) ?: return
        if (bestLocation != lastLocation) lastLocation = bestLocation
    }

    private fun getBestLocation(location: Location): Location? {
        if (lastLocation == null) return location
        val older =
            (if ((lastLocation?.time ?: 0L) < location.time) lastLocation else location)
                ?: return null
        val newer =
            (if (lastLocation == older) location else lastLocation) ?: return null
        if (older.accuracy <= newer.accuracy) return newer
        return if (newer.distanceTo(older) < newer.accuracy) older else newer
    }


    private fun Context.permissionNotGranted(permission: String) =
        ActivityCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED

    companion object {
        var lastLocation: Location? = null
    }
}

Upvotes: 2

Related Questions