android中获取定位信息的方式有很多种,系统自带的locationmanager,以及第三方厂商提供的一些定位sdk,都能帮助我们获取当前经纬度,但第三方厂商一般都需要申请相关的key,且调用量高时,还会产生资费问题。这里采用locationmanager + fusedlocationproviderclient 的方式进行经纬度的获取,以解决普通场景下获取经纬度和经纬度转换地址的功能。
一,添加定位权限
<!--允许获取精确位置,精准定位必选--> <uses-permission android:name="android.permission.access_fine_location" /> <uses-permission android:name="android.permission.access_coarse_location" /> <!--后台获取位置信息,若需后台定位则必选--> <uses-permission android:name="android.permission.access_background_location" /> <!--用于申请调用a-gps模块,卫星定位加速--> <uses-permission android:name="android.permission.access_location_extra_commands" />
二,添加依赖库
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.6.2'
implementation 'com.google.android.gms:play-services-location:21.0.1'三,使用locationmanager获取当前经纬度
获取经纬度时,可根据自己的诉求进行参数自定义,如果对经纬度要求不是很精确的可以自行配置criteria里面的参数。
获取定位前需要先判断相关的服务是否可用,获取定位的服务其实有很多种选择,因为个人项目对经纬度准确性要求较高,为了保证获取的成功率和准确性,只使用了gps和网络定位两种,如果在国内还会有基站获取等方式,可以自行修改。
import android.manifest.permission
import android.location.*
import android.os.bundle
import android.util.log
import androidx.annotation.requirespermission
import kotlinx.coroutines.suspendcancellablecoroutine
import kotlinx.coroutines.withtimeout
import kotlin.coroutines.resume
object locationmanagerutils {
val tag = "locationmanagerutils"
/**
* @mlocationmanager 传入locationmanager对象
* @mindistance 位置变化最小距离:当位置距离变化超过此值时,将更新位置信息(单位:米)
* @timeout 超时时间,如果超时未返回,则直接使用默认值
*/
@requirespermission(anyof = [permission.access_coarse_location, permission.access_fine_location])
suspend fun getcurrentposition(
mlocationmanager: locationmanager,
timeout: long = 3000,
):location{
var locationlistener : locationlistener?=null
return try {
//超时未返回则直接获取失败,返回默认值
withtimeout(timeout){
suspendcancellablecoroutine {continuation ->
//获取最佳定位方式,如果获取不到则默认采用网络定位。
var bestprovider = mlocationmanager.getbestprovider(createcriteria(),true)
if (bestprovider.isnullorempty()||bestprovider == "passive"){
bestprovider = "network"
}
log.d(tag, "getcurrentposition:bestprovider:${bestprovider}")
locationlistener = object : locationlistener {
override fun onlocationchanged(location: location) {
log.d(tag, "getcurrentposition:oncompete:${location.latitude},${location.longitude}")
if (continuation.isactive){
continuation.resume(location)
mlocationmanager.removeupdates(this)
}
}
override fun onproviderdisabled(provider: string) {
}
override fun onproviderenabled(provider: string) {
}
}
//开始定位
mlocationmanager.requestlocationupdates(bestprovider,
1000,0f,
locationlistener!!)
}
}
}catch (e:exception){
try {
locationlistener?.let {
mlocationmanager.removeupdates(it)
}
}catch (e:exception){
log.d(tag, "getcurrentposition:removeupdate:${e.message}")
}
//超时直接返回默认的空对象
log.d(tag, "getcurrentposition:onerror:${e.message}")
return createdefaultlocation()
}
}
@requirespermission(anyof = [permission.access_coarse_location, permission.access_fine_location])
suspend fun repeatlocation(mlocationmanager: locationmanager):location{
return suspendcancellablecoroutine {continuation ->
//获取最佳定位方式,如果获取不到则默认采用网络定位。
var bestprovider = mlocationmanager.getbestprovider(createcriteria(),true)
if (bestprovider.isnullorempty()||bestprovider == "passive"){
bestprovider = "network"
}
log.d(tag, "getcurrentposition:bestprovider:${bestprovider}")
val locationlistener = object : locationlistener {
override fun onlocationchanged(location: location) {
log.d(tag, "getcurrentposition:oncompete:${location.latitude},${location.longitude}")
if (continuation.isactive){
continuation.resume(location)
}
mlocationmanager.removeupdates(this)
}
override fun onproviderdisabled(provider: string) {
}
override fun onproviderenabled(provider: string) {
}
}
//开始定位
mlocationmanager.requestlocationupdates(bestprovider,1000, 0f, locationlistener)
}
}
@requirespermission(anyof = [permission.access_coarse_location, permission.access_fine_location])
fun getlastlocation( mlocationmanager: locationmanager): location {
//获取最佳定位方式,如果获取不到则默认采用网络定位。
var currentprovider = mlocationmanager.getbestprovider(createcriteria(), true)
if (currentprovider.isnullorempty()||currentprovider == "passive"){
currentprovider = "network"
}
return mlocationmanager.getlastknownlocation(currentprovider) ?: createdefaultlocation()
}
//创建定位默认值
fun createdefaultlocation():location{
val location = location("network")
location.longitude = 0.0
location.latitude = 0.0
return location
}
private fun createcriteria():criteria{
return criteria().apply {
accuracy = criteria.accuracy_fine
isaltituderequired = false
isbearingrequired = false
iscostallowed = true
powerrequirement = criteria.power_high
isspeedrequired = false
}
}
///定位是否可用
fun checklocationmanageravailable(mlocationmanager: locationmanager):boolean{
return mlocationmanager.isproviderenabled(locationmanager.network_provider)||
mlocationmanager.isproviderenabled(locationmanager.gps_provider)
}
}四,使用fusedlocationproviderclient
在获取经纬度时会出现各种异常的场景,会导致成功的回调一直无法触发,这里使用了协程,如果超过指定超时时间未返回,则直接默认为获取失败,进行下一步的处理。
import android.manifest
import android.app.activity
import android.content.context
import android.content.context.location_service
import android.content.intent
import android.location.geocoder
import android.location.location
import android.location.locationmanager
import android.provider.settings
import android.util.log
import androidx.annotation.requirespermission
import com.google.android.gms.location.locationservices
import kotlinx.coroutines.dispatchers
import kotlinx.coroutines.suspendcancellablecoroutine
import kotlinx.coroutines.withcontext
import kotlinx.coroutines.withtimeout
import java.io.ioexception
import java.util.*
import kotlin.coroutines.resume
object fusedlocationproviderutils {
val tag = "fusedlocationutils"
@requirespermission(anyof = ["android.permission.access_coarse_location", "android.permission.access_fine_location"])
suspend fun checkfusedlocationprovideravailable(fusedlocationclient: fusedlocationproviderclient):boolean{
return try {
withtimeout(1000){
suspendcancellablecoroutine { continuation ->
fusedlocationclient.locationavailability.addonfailurelistener {
log.d(tag, "locationavailability:addonfailurelistener:${it.message}")
if (continuation.isactive){
continuation.resume(false)
}
}.addonsuccesslistener {
log.d(tag, "locationavailability:addonsuccesslistener:${it.islocationavailable}")
if (continuation.isactive){
continuation.resume(it.islocationavailable)
}
}
}
}
}catch (e:exception){
return false
}
}
///获取最后已知的定位信息
@requirespermission(anyof = ["android.permission.access_coarse_location", "android.permission.access_fine_location"])
suspend fun getlastlocation(fusedlocationclient: fusedlocationproviderclient):location{
return suspendcancellablecoroutine {continuation ->
fusedlocationclient.lastlocation.addonsuccesslistener {
if (continuation.isactive){
log.d(tag, "current location success:$it")
if (it != null){
continuation.resume(it)
}else{
continuation.resume(createdefaultlocation())
}
}
}.addonfailurelistener {
continuation.resume(createdefaultlocation())
}
}
}
/**
* 获取当前定位,需要申请定位权限
*
*/
@requirespermission(anyof = ["android.permission.access_coarse_location", "android.permission.access_fine_location"])
suspend fun getcurrentposition(fusedlocationclient: fusedlocationproviderclient): location {
return suspendcancellablecoroutine {continuation ->
fusedlocationclient.getcurrentlocation(createlocationrequest(),object : cancellationtoken(){
override fun oncanceledrequested(p0: ontokencanceledlistener): cancellationtoken {
return cancellationtokensource().token
}
override fun iscancellationrequested(): boolean {
return false
}
}).addonsuccesslistener {
if (continuation.isactive){
log.d(tag, "current location success:$it")
if (it != null){
continuation.resume(it)
}else{
continuation.resume(createdefaultlocation())
}
}
}.addonfailurelistener {
log.d(tag, "current location fail:$it")
if (continuation.isactive){
continuation.resume(createdefaultlocation())
}
}.addoncanceledlistener {
log.d(tag, "current location cancel:")
if (continuation.isactive){
continuation.resume(createdefaultlocation())
}
}
}
}
//创建当前locationrequest对象
private fun createlocationrequest():currentlocationrequest{
return currentlocationrequest.builder()
.setdurationmillis(1000)
.setmaxupdateagemillis(5000)
.setpriority(priority.priority_high_accuracy)
.build()
}
//创建默认值
private fun createdefaultlocation():location{
val location = location("network")
location.longitude = 0.0
location.latitude = 0.0
return location
}
}五,整合locationmanager和fusedlocationproviderclient
在获取定位时,可能会出现gps定位未开启的情况,所以不管是locationmanager或fusedlocationproviderclient都需要判断当前服务是否可用,获取定位时,如果gps信号较弱等异常情况下,就需要考虑到获取定位超时的情况,这里使用了协程,如fusedlocationproviderclient超过3秒未获取成功,则直接切换到locationmanager进行二次获取,这是提升获取经纬度成功的关键。
在实际项目中,如果对获取经纬度有较高的考核要求时,通过结合locationmanager和fusedlocationproviderclient如果还是获取不到,可考虑集成第三方的进行进一步获取,可以考虑使用华为的免费融合定位服务,因为我们使用过百度地图的sdk,每天会出现千万分之五左右的定位错误和定位漂移问题。
import android.manifest
import android.app.activity
import android.content.context
import android.content.context.location_service
import android.content.intent
import android.location.geocoder
import android.location.location
import android.location.locationmanager
import android.provider.settings
import android.util.log
import androidx.annotation.requirespermission
import com.google.android.gms.location.locationservices
import kotlinx.coroutines.dispatchers
import kotlinx.coroutines.suspendcancellablecoroutine
import kotlinx.coroutines.withcontext
import kotlinx.coroutines.withtimeout
import java.io.ioexception
import java.util.*
import kotlin.coroutines.resume
object locationhelper {
fun getlocationservicestatus(context: context):boolean{
return (context.getsystemservice(location_service) as locationmanager)
.isproviderenabled(locationmanager.gps_provider)
}
/**
* 打开定位服务设置
*/
fun openlocationsetting(context: context):boolean{
return try {
val settingsintent = intent()
settingsintent.action = settings.action_location_source_settings
settingsintent.addcategory(intent.category_default)
settingsintent.addflags(intent.flag_activity_new_task)
settingsintent.addflags(intent.flag_activity_no_history)
settingsintent.addflags(intent.flag_activity_exclude_from_recents)
context.startactivity(settingsintent)
true
} catch (ex: java.lang.exception) {
false
}
}
/**
* 获取当前定位
*/
@requirespermission(anyof = [manifest.permission.access_coarse_location, manifest.permission.access_fine_location])
suspend fun getlocation(context: activity,timeout: long = 2000):location{
val location = getlocationbyfusedlocationproviderclient(context)
//默认使用fusedlocationproviderclient 如果fusedlocationproviderclient不可用或获取失败,则使用locationmanager进行二次获取
log.d("locationhelper", "getlocation:$location")
return if (location.latitude == 0.0){
getlocationbylocationmanager(context, timeout)
}else{
location
}
}
@requirespermission(anyof = [manifest.permission.access_coarse_location, manifest.permission.access_fine_location])
private suspend fun getlocationbylocationmanager(context: activity,timeout: long = 2000):location{
log.d("locationhelper", "getlocationbylocationmanager")
val locationmanager = context.getsystemservice(location_service) as locationmanager
//检查locationmanager是否可用
return if (locationmanagerutils.checklocationmanageravailable(locationmanager)){
//使用locationmanager获取当前经纬度
val location = locationmanagerutils.getcurrentposition(locationmanager, timeout)
if (location.latitude == 0.0){
locationmanagerutils.getlastlocation(locationmanager)
}else{
location
}
}else{
//获取失败,则采用默认经纬度
locationmanagerutils.createdefaultlocation()
}
}
@requirespermission(anyof = [manifest.permission.access_coarse_location, manifest.permission.access_fine_location])
private suspend fun getlocationbyfusedlocationproviderclient(context: activity):location{
log.d("locationhelper", "getlocationbyfusedlocationproviderclient")
//使用fusedlocationproviderclient进行定位
val fusedlocationclient = locationservices.getfusedlocationproviderclient(context)
return if (fusedlocationproviderutils.checkfusedlocationprovideravailable(fusedlocationclient)){
withcontext(dispatchers.io){
//使用fusedlocationproviderclient获取当前经纬度
val location = fusedlocationproviderutils.getcurrentposition(fusedlocationclient)
if (location.latitude == 0.0){
fusedlocationproviderutils.getlastlocation(fusedlocationclient)
}else{
location
}
}
}else{
locationmanagerutils.createdefaultlocation()
}
}
}注:因为获取定位是比较耗电的操作,在实际使用时,可增加缓存机制,比如2分钟之内频繁,则返回上一次缓存的数据,如果超过2分钟则重新获取一次,并缓存起来。
六,获取当前经纬度信息或经纬度转换地址
1,获取当前经纬度
@requirespermission(anyof = [manifest.permission.access_coarse_location, manifest.permission.access_fine_location])
fun getcurrentlocation(activity:activity){
if (activity != null){
val exceptionhandler = coroutineexceptionhandler { _, exception ->
}
viewmodelscope.launch(exceptionhandler) {
val location = locationhelper.getlocation(activity!!)
val map = hashmap<string,string>()
map["latitude"] ="${location.latitude}"
map["longitude"] = "${location.longitude}"
}
}
}2,经纬度转换地址
/**
* @param latitude 经度
* @param longitude 纬度
* @return 详细位置信息
*/
suspend fun convertaddress(context: context, latitude: double, longitude: double): string {
return try {
withtimeout(3000){
suspendcancellablecoroutine { continuation ->
try {
val mgeocoder = geocoder(context, locale.getdefault())
val mstringbuilder = stringbuilder()
if (geocoder.ispresent()){
val maddresses = mgeocoder.getfromlocation(latitude, longitude, 1)
if (maddresses!= null &&maddresses.size >0) {
val address = maddresses[0]
log.d("locationutils", "convertaddress()--->$address")
mstringbuilder.append(address.getaddressline(0)?:"")
.append(",")
.append(address.adminarea?:address.subadminarea?:"")
.append(",")
.append(address.locality?:address.sublocality?:"")
.append(",")
.append(address.thoroughfare?:address.subthoroughfare?:"")
}
}
if (continuation.isactive){
continuation.resume(mstringbuilder.tostring())
}
} catch (e: ioexception) {
log.d("locationutils", "convertaddress()--ioexception->${e.message}")
if (continuation.isactive){
continuation.resume("")
}
}
}
}
}catch (e:exception){
log.d("locationutils", "convertaddress()--->timeout")
return ""
}
}调用时:
fun covertaddress(latitude:double,longitude:double){
if (activity != null){
val exceptionhandler = coroutineexceptionhandler { _, exception ->
}
viewmodelscope.launch(exceptionhandler) {
val hashmap = argument as hashmap<*, *>
withcontext(dispatchers.io){
val address = locationhelper.convertaddress(activity!!,
"${hashmap["latitude"]}".todouble(),
"${hashmap["longitude"]}".todouble())
}
}
}
}注:经纬度转换地址时,需要开启一个线程或者协程进行转换,不然会阻塞主线程,引发异常。
到此这篇关于android获取经纬度的最佳实现方式的文章就介绍到这了,更多相关android获取经纬度内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论