You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

克隆Uber时requestLocationUpdates方法无法解析问题求助

问题描述

我正在复刻Uber应用,需要获取司机的实时位置,但调用LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient,locationRequest,this);时出现错误:

Cannot resolve method 'requestLocationUpdates(com.google.android.gms.common.api.GoogleApiClient, android.location.LocationRequest, com.example.codingcafe.cab.DriversMapActivity)'

我已经尝试在类中实现LocationListener、修改build.gradle中的gms-location依赖,但都没解决问题。以下是我的代码:

package com.example.codingcafe.cab;


import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationRequest;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;

import com.example.codingcafe.cab.databinding.ActivityDriversMapBinding;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.location.LocationListener;

public class DriversMapActivity extends FragmentActivity implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        com.google.android.gms.location.LocationListener{

    private GoogleMap mMap;
    private ActivityDriversMapBinding binding;
    GoogleApiClient googleApiClient;
    Location LastLocation;
    LocationRequest locationRequest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityDriversMapBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney,17));
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            locationRequest = new LocationRequest.Builder( 1000)
                    .setMinUpdateIntervalMillis(500)
                    .setQuality(LocationRequest.QUALITY_HIGH_ACCURACY)
                    .setMaxUpdateDelayMillis(1000)
                    .build();

        }

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
        {
            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient,locationRequest,this);

        //it will handle the refreshment of the location
        //if we dont call it we will get location only once

    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    @Override
    public void onLocationChanged(Location location) {

    }
}
错误原因&修复方案

核心问题

  1. 废弃API混用:LocationServices.FusedLocationApi是已淘汰的旧版定位API,Google现在推荐使用FusedLocationProviderClient替代。
  2. LocationRequest类型不匹配:你导入的是系统自带的android.location.LocationRequest,但Google定位API需要的是com.google.android.gms.location.LocationRequest。
  3. GoogleApiClient未初始化:代码仅声明了GoogleApiClient变量,但没有完成构建和连接流程,导致调用时为空对象。

修复步骤

  1. 替换废弃的FusedLocationApi为FusedLocationProviderClient,使用现代定位API。
  2. 修正LocationRequest的导入,使用Google定位库的版本。
  3. 在onCreate中完成GoogleApiClient的构建与连接。
  4. 补充权限申请逻辑,适配Android动态权限机制。

修复后的完整代码

package com.example.codingcafe.cab;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;

import com.example.codingcafe.cab.databinding.ActivityDriversMapBinding;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class DriversMapActivity extends FragmentActivity implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {

    private GoogleMap mMap;
    private ActivityDriversMapBinding binding;
    private GoogleApiClient googleApiClient;
    private Location lastLocation;
    private LocationRequest locationRequest;
    private FusedLocationProviderClient fusedLocationClient;
    private LocationCallback locationCallback;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityDriversMapBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // 初始化现代定位客户端
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

        // 构建并连接GoogleApiClient
        buildGoogleApiClient();

        // 设置位置更新回调
        locationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(@NonNull LocationResult locationResult) {
                super.onLocationResult(locationResult);
                if (locationResult == null) return;
                // 更新最新位置并刷新地图
                lastLocation = locationResult.getLastLocation();
                updateDriverLocation(lastLocation);
            }
        };

        // 获取地图实例
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    // 构建GoogleApiClient
    protected synchronized void buildGoogleApiClient() {
        googleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        googleApiClient.connect();
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        // 初始位置标记
        LatLng initialPos = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(initialPos).title("司机位置"));
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(initialPos, 17));
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        // 创建LocationRequest(适配Android 12+)
        locationRequest = new LocationRequest.Builder(1000)
                .setMinUpdateIntervalMillis(500)
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setMaxUpdateDelayMillis(1000)
                .build();

        // 检查定位权限
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // 动态申请权限
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 100);
            return;
        }

        // 开始请求实时位置更新
        fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
    }

    // 更新地图上的司机位置
    private void updateDriverLocation(Location location) {
        if (location != null && mMap != null) {
            LatLng driverPos = new LatLng(location.getLatitude(), location.getLongitude());
            mMap.clear();
            mMap.addMarker(new MarkerOptions().position(driverPos).title("当前司机位置"));
            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(driverPos, 17));
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
        googleApiClient.connect();
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        // 处理连接失败逻辑,比如提示用户检查Google Play服务
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 100) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限授权成功后重新发起位置请求
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
                }
            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        // 停止位置更新,避免后台耗电
        if (fusedLocationClient != null) {
            fusedLocationClient.removeLocationUpdates(locationCallback);
        }
    }
}

额外配置说明

  • 依赖版本:确保Module级build.gradle中使用最新的Google服务依赖:
    implementation 'com.google.android.gms:play-services-location:21.0.1'
    implementation 'com.google.android.gms:play-services-maps:18.2.0'
    
  • Manifest权限:在AndroidManifest.xml中添加必要权限:
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <!-- 若需要后台定位,添加以下权限(Android 12+) -->
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
    

内容的提问来源于stack exchange,提问作者Mohamad Software

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 19:55:11