Android 获取定位信息工具类

相信大家在项目中应该会经常用到这类功能,需要在请求api的时候获取当前定位信息,以便获取周边信息,以下是我常用的工具类,大家应该用得上

kotlin 复制代码
import android.annotation.SuppressLint;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.os.Handler;
import android.os.Looper;

import androidx.annotation.NonNull;


/**
 * 描述: 获取定位信息
 * 创建者: IT乐手
 * 日期: 2025/5/21
 */

public class LocationUtils {

    private final static String TAG = "LocationUtils";

    private static double latitude = 22.665424;
    private static double longitude = 114.075724;

    private static LocationManager locationManager = null;
    private static final Handler mainHandler = new Handler(Looper.getMainLooper());

    /**
     * 获取经纬度
     * @return 经纬度字符串
     */
    public static String getLocationString() {
        double[] locations = getLocation();
        String locationStr = locations[0]+","+locations[1];
        AtotoLogger.d(TAG, locationStr);
        return locationStr;
    }

    @SuppressLint("MissingPermission")
    public static double[] getLocation() {
        if (locationManager == null) {
            locationManager = (LocationManager) AppGlobalUtils.getApplication().getSystemService(Context.LOCATION_SERVICE);
        }
        // 检查GPS/网络是否可用
        boolean hasGps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean hasNetwork = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        boolean hasPassive = locationManager.isProviderEnabled(LocationManager.PASSIVE_PROVIDER);
        AtotoLogger.d(TAG, "hasGps = " + hasGps + ", hasNetwork = " + hasNetwork + ", hasPassive = " + hasPassive);
        if (!hasGps && !hasNetwork) {
            AtotoLogger.e(TAG, "Gps and Network are not available");
            return new double[]{0,0};
        }

        Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        if (location == null) {
            AtotoLogger.d(TAG, "GPS location is null, trying Network location");
            location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        }

        if (location == null) {
            AtotoLogger.e(TAG, "Location is null");
            // 在主线程中请求位置更新
            if (Looper.myLooper() == Looper.getMainLooper()) {
                requestLocationUpdatesOnCurrentThread();
            } else {
                mainHandler.post(LocationUtils::requestLocationUpdatesOnCurrentThread);
            }
            return new double[]{latitude,longitude};
        }

        latitude = location.getLatitude();
        longitude = location.getLongitude();
        AtotoLogger.d(TAG, "Latitude: " + latitude + ", Longitude: " + longitude);
        // 处理经纬度信息
        return new double[]{latitude, longitude};
    }

    @SuppressLint("MissingPermission")
    private static void requestLocationUpdatesOnCurrentThread() {
        try {
            locationManager.requestLocationUpdates(
                    LocationManager.PASSIVE_PROVIDER,
                    0, // minTime (milliseconds)
                    0,   // minDistance (meters)
                    locationListener
            );
        } catch (Exception e) {
            AtotoLogger.e(TAG, "Request location updates failed: " + e.getMessage());
        }
    }

    private static final android.location.LocationListener locationListener = new android.location.LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
            AtotoLogger.d(TAG, "Location updated: Latitude: " + latitude + ", Longitude: " + longitude);

            // 获取到位置后移除监听,避免持续更新
            removeLocationUpdates();
        }

        @Override
        public void onStatusChanged(String provider, int status, android.os.Bundle extras) {
        }

        @Override
        public void onProviderEnabled(@NonNull String provider) {
        }

        @Override
        public void onProviderDisabled(@NonNull String provider) {
        }
    };

    /**
     * 移除位置更新监听
     */
    public static void removeLocationUpdates() {
        if (locationManager != null) {
            try {
                locationManager.removeUpdates(locationListener);
            } catch (Exception e) {
                AtotoLogger.e(TAG, "Remove location updates failed: " + e.getMessage());
            }
        }
    }


    @SuppressLint("MissingPermission")
    private static Location getLastKnownLocation() {
        if (locationManager == null) return null;

        Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (location == null) {
            location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        }
        return location;
    }
}
相关推荐
Zender Han4 小时前
Flutter 新版 Google Sign-In 插件完整解析(含示例讲解)
android·flutter·ios·web
来来走走8 小时前
Android开发(Kotlin) LiveData的基本了解
android·开发语言·kotlin
。puppy9 小时前
MySQL 远程登录实验:通过 IP 地址跨机器连接实战指南
android·adb
dongdeaiziji9 小时前
深入理解 Kotlin 中的构造方法
android·kotlin
风起云涌~10 小时前
【Android】浅谈Navigation
android
游戏开发爱好者810 小时前
iOS 商店上架全流程解析 从工程准备到审核通过的系统化实践指南
android·macos·ios·小程序·uni-app·cocoa·iphone
QuantumLeap丶12 小时前
《Flutter全栈开发实战指南:从零到高级》- 18 -自定义绘制与画布
android·flutter·ios
.豆鲨包12 小时前
【Android】 View事件分发机制源码分析
android·java
花落归零13 小时前
Android 小组件AppWidgetProvider的使用
android
弥巷13 小时前
【Android】常见滑动冲突场景及解决方案
android·java