安卓使用谷歌定位服务获取经纬度

发布于:2025-04-17 ⋅ 阅读:(61) ⋅ 点赞:(0)

权限:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

依赖:

    // 谷歌定位服务
    implementation 'com.google.android.gms:play-services-location:21.0.1'
    
    /**
     * rxPermission
     * https://github.com/tbruyelle/RxPermissions
     */
    implementation 'com.github.tbruyelle:rxpermissions:0.10.2'

使用:

// 检查定位权限(不直接申请权限是因为这个功能在首页,直接申请权限应用市场会不通过)
if (ContextCompat.checkSelfPermission(Objects.requireNonNull(getContext()), Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(Objects.requireNonNull(getContext()), Manifest.permission.ACCESS_COARSE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            // 获取经纬度
            getLocation();
        }
    /**
     * 获取经纬度
     */
    private void getLocation() {
        RxPermissions rxPermission = new RxPermissions(this);
        Disposable disposable = rxPermission.request(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) {
                        if (aBoolean) {
                            FusedLocationProviderClient client = LocationServices.getFusedLocationProviderClient(Objects.requireNonNull(getContext()));
                            client.getLastLocation().addOnSuccessListener(location -> {
                                if (location != null) {
                                    mLatitude = String.valueOf(location.getLatitude());
                                    mLongitude = String.valueOf(location.getLongitude());
                                    Logger.d("Latitude: " + mLatitude + ", Longitude: " + mLongitude);
                                }
                            });
                        } else {
                            // 权限被拒
                        }
                    }
                });
    }

网站公告

今日签到

点亮在社区的每一天
去签到