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;
    }
}
相关推荐
yangjunjin3 小时前
Android ANR的解决方案
android
低调小一3 小时前
Android Gradle 的 compileOptions 与 Kotlin jvmTarget 全面理解(含案例)
android·开发语言·kotlin
苦学编程啊7 小时前
【2025Flutter 入门指南】Dart SDK 安装与 VS Code 环境配置-Windows
android·dart
yuanManGan13 小时前
走进Linux的世界:初识操作系统(Operator System)
android·linux·运维
叶羽西14 小时前
Android15跟踪函数调用关系
android
消失的旧时光-194315 小时前
webView 的canGoBack/goBack 回退栈
android·webview
SHEN_ZIYUAN15 小时前
Flow 责任链模式图解
android
沐怡旸17 小时前
【底层机制】LeakCanary深度解析:从对象监控到内存泄漏分析的完整技术体系
android·面试
又菜又爱coding17 小时前
Android + Flutter打包出来的APK体积太大
android·flutter