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;
    }
}
相关推荐
Lei活在当下4 小时前
【项目踩坑实录】并发环境下,Glide缓存引起的图片加载异常
android·debug·glide
my_power5207 小时前
检出git项目到android studio该如何配置
android·git·android studio
三少爷的鞋10 小时前
Repository 方法设计:suspend 与 Flow 的决选择指南(以朋友圈为例)
android
阿里云云原生10 小时前
Android App 崩溃排查指南:阿里云 RUM 如何让你快速从告警到定位根因?
android·java
cmdch201712 小时前
手持机安卓新增推送按钮功能
android
攻城狮201512 小时前
【rk3528/rk3518 android14 kernel-6.10 emcp sdk】
android
何妨呀~12 小时前
mysql 8服务器实验
android·mysql·adb
QuantumLeap丶13 小时前
《Flutter全栈开发实战指南:从零到高级》- 25 -性能优化
android·flutter·ios
木易 士心15 小时前
MVC、MVP 与 MVVM:Android 架构演进之路
android·架构·mvc
百锦再15 小时前
国产数据库的平替亮点——关系型数据库架构适配
android·java·前端·数据库·sql·算法·数据库架构