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;
    }
}
相关推荐
李坤林13 小时前
Android Binder 详解(6) Binder 客户端的创建
android·binder
北京自在科技13 小时前
苹果iOS 26.3实现跨安卓数据无缝迁移
android·ios·findmy
_道隐_13 小时前
Android里面的layer、DisplayList和hardwarebuffer之间是什么关系
android
stevenzqzq15 小时前
ctrl +B和ctrl+shift +B的区别
android·ide·android studio
似霰15 小时前
HIDL Hal 开发笔记5----Same-Process HALs 实例分析
android·framework·hal
robotx16 小时前
安卓16 设置壁纸中应用网格,有两个5X5的选项
android
Yyuanyuxin16 小时前
保姆级学习开发安卓手机软件(三)--安装模拟机并开始简单的进入开发
android·学习
Android小码家16 小时前
llama.cpp+Android应用定制
android·llama
龚礼鹏16 小时前
Android应用程序 c/c++ 崩溃排查流程二——AddressSanitizer工具使用
android·c语言·c++
Android-Flutter16 小时前
android compose DropdownMenu 菜单项列表 使用
android