添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
  • 可用设备系统:鸿蒙2.0、华为Android10+、小米Android10+(其他设备未测试)
  • 开发工具:android studio 2020.3.1 Patch4
  • 开发语言:kotlin
package cn.cb.andbase.activity
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.location.Geocoder
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import android.widget.Button
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import cn.cb.andbase.R
import cn.cb.baselibrary.activity.BaseActivity
import cn.cb.baselibrary.utils.LogHelper
import com.hjq.toast.ToastUtils
import java.util.*
private const val TAG = "LocationActivity"
class LocationActivity : BaseActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_location)
        initBarView()
        LocationHelper.instance.create(this)
        findViewById<Button>(R.id.location_default_get).setOnClickListener {
            LocationHelper.instance.getLocation()
        findViewById<Button>(R.id.location_default_address).setOnClickListener {
            addMsg(getAddress(this, 114.31828880795926, 30.471368343906683))
    override fun onDestroy() {
        super.onDestroy()
        LocationHelper.instance.removeListener()
    var resumeTimes = 0
    override fun onResume() {
        super.onResume()
        resumeTimes++
        if (resumeTimes < 3) launcher.launch(permission)
    private val permission = arrayOf(
        android.Manifest.permission.ACCESS_FINE_LOCATION,
        android.Manifest.permission.ACCESS_COARSE_LOCATION
    private val launcher =
        registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
            for (v in it.values) if (!v) {
                AlertDialog.Builder(this)
                    .setMessage("权限不足!")
                    .setPositiveButton("去设置") { _, _ ->
                        goSettingActivity(this)
                    }.show()
                return@registerForActivityResult
    private fun goSettingActivity(context: Context) {
        val intent = Intent()
        intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
        intent.data = Uri.parse("package:" + context.packageName)
        context.startActivity(intent)
    private fun getAddress(context: Context, lnt: Double, lat: Double): String {
        val geocoder = Geocoder(context, Locale.CHINA)
        val flag = Geocoder.isPresent()
        if (!flag) {
            LogHelper.w(TAG, "Geocoder Present is $flag")
            return ""
        val sb = StringBuilder()
        val addresses = geocoder.getFromLocation(lat, lnt, 1)
        if (addresses.isNullOrEmpty()) return ""
        for (address in addresses) {
            LogHelper.w(TAG, "address: $address")
            sb.append(address.countryName)
                .append(address.adminArea)
                .append(address.locality)
                .append(address.subAdminArea)
                .append(address.thoroughfare)
                .append(address.featureName)
        return sb.toString()
    class LocationHelper {
        private val tag = javaClass.simpleName
        private lateinit var locationManager: LocationManager
        companion object {
            val instance = LocationHelper()
        fun create(context: Context) {
            locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        @SuppressLint("MissingPermission")
        fun getLocation() {
            val provides = locationManager.allProviders
            var provideStr = ""
            for (provide in provides) when (provide) {
                LocationManager.NETWORK_PROVIDER -> {
                    provideStr = LocationManager.NETWORK_PROVIDER
                    break
                LocationManager.GPS_PROVIDER -> {
                    provideStr = LocationManager.GPS_PROVIDER
                    break
                else -> provideStr = ""
            if (provideStr.isBlank()) {
                ToastUtils.show("无法获取定位")
                return
            val location = locationManager.getLastKnownLocation(provideStr)
            location?.also { setLocation(it) }
            locationManager.requestLocationUpdates(provideStr, 0L, 0F, listener)
        private val listener = LocationListener {
            LogHelper.w(tag, "accuracy: ${it.accuracy}")
            setLocation(it)
        fun setLocation(location: Location) {
            LogHelper.w(tag, "latitude: " + location.latitude + "\tlongitude:" + location.longitude)
        fun removeListener() {
            locationManager.removeUpdates(listener)
    companion object {
        val handler = Handler(Looper.getMainLooper())
    fun addMsg(msg: String) {
        val logTv = findViewById<TextView>(R.id.print_log)
        val handler = Handler(Looper.getMainLooper()) {
            val sb = StringBuilder().append(it.obj).appendLine().appendLine().append(logTv.text)
            logTv.text = sb.toString()
            return@Handler true
        handler.post {
            handler.obtainMessage(0, 0, 0, msg).let { handler.dispatchMessage(it) }
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".activity.LocationActivity">
    <include layout="@layout/tool_bar" />
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toBottomOf="@id/tool_bar_view">
        <TextView
            android:id="@+id/print_log"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="end" />
    </ScrollView>
    <Button
        android:id="@+id/location_default_get"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="get location"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toBottomOf="@id/tool_bar_view" />
    <Button
        android:id="@+id/location_default_address"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="get address"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toBottomOf="@id/location_default_get" />
</androidx.constraintlayout.widget.ConstraintLayout>

源码地址gitee
文章地址:https://blog.csdn.net/qq471208499/article/details/121910319

赠人玫瑰,手有余香

假如你觉得项目有用,可以收藏点赞哦!!!

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <!-- 如果需要精确定位的话请加上此权限 --> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <! LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 在使用到百度地图经纬度地址相互换的时候,我们最最最首先需要的是集成百度地图,让我们的APP能够拥有百度的jar包功能,然后在我们所需要换的activity或者fragment中implements OnGetGeoCoderResultListener,这样我们就可以进行下一步的操作开发了(╹▽╹)private GeoCoder mSearch = null; // 搜索模块,也可去掉地图... 1.地理编码查询接口是单列模式的,我们需要调用让它自己实例化// 在OnCreate方法里创建地理编码检索实例GeoCoder geoCoder = GeoCoder.newInstance();2.调用这个方法把你想要的经纬度传入/** * 经纬度地址相互换** @param latlng*/private void latlngToAddress(LatLng latlng) {// 设置... 文章目录一、定位介绍二、代码1、实例化LocationManager2、处理运行时权限3、开始请求定位4、定位监听器5、更新定位三、Demo下载 一、定位介绍 在不使用第三方地图SDK的情况下,也可以借助Android 本身的定位API来实现相关地理位置功能更,官方介绍见这里(需要翻墙):https://developer.android.com/reference/android/locatio... android:name="android.permission.ACCESS_COARSE_LOCATION" android:name="android.permission.ACCESS_FINE_LOCATION" 1.1其次最重要的是,申请权限,一直真机调试不成功,折磨死我啦,放在protected void o        实现经纬度地址信息,主要用到的类是GeoCoder,通过newInstance获得类的实例。        用到的方法为 public boolean reverseGeoCode(ReverseGeoCodeOption option)即反向解析,发起反地理编码请求(经纬度->地址信息)        与其对应的是方法为 public boolean