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

FusedLocationApi已弃用致Google Maps应用授权后崩溃求助

Fixing Google Maps App Crash After Location Permission Grant

Hey there, let's figure out why your app crashes right after granting location permissions. The deprecated FusedLocationApi is almost certainly the main culprit here, and switching to Google's modern location tools will resolve this. Let's break down the fixes step by step:

1. Replace Deprecated FusedLocationApi with Modern FusedLocationProviderClient

Google has fully phased out FusedLocationApi in favor of FusedLocationProviderClient—this outdated API is the root cause of your compatibility crashes. Here's how to update your code:

Step 1: Add the New Client as a Member Variable

Add this line to your MapsActivity class:

private FusedLocationProviderClient fusedLocationClient;

Step 2: Initialize the Client

Set it up in your onCreate method (you can even ditch the old GoogleApiClient setup entirely—it's no longer needed):

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    
    // Initialize the modern location client
    fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        checkLocationPermission();
    }
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}

Step 3: Update Location Update Logic

Remove the old GoogleApiClient related methods (like buildGoogleApiClient, onConnected) and replace them with a dedicated method to start location updates:

private void startLocationUpdates() {
    myLocationRequest = new LocationRequest();
    myLocationRequest.setInterval(1000);
    myLocationRequest.setFastestInterval(1000);
    myLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

    // Use the modern client to request updates
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        fusedLocationClient.requestLocationUpdates(myLocationRequest, locationCallback, Looper.getMainLooper());
    }
}

Step 4: Use LocationCallback Instead of Old LocationListener

Replace the deprecated listener with a modern callback to handle location updates safely:

private LocationCallback locationCallback = new LocationCallback() {
    @Override
    public void onLocationResult(LocationResult locationResult) {
        super.onLocationResult(locationResult);
        if (locationResult == null || mMap == null) {
            return; // Guard against null map or location data to avoid crashes
        }
        
        myLastLocation = locationResult.getLastLocation();
        if (myCurrLocationMarker != null) {
            myCurrLocationMarker.remove();
        }

        LatLng latLng = new LatLng(myLastLocation.getLatitude(), myLastLocation.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title("My Position");
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
        myCurrLocationMarker = mMap.addMarker(markerOptions);

        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(11));

        // Stop updates if you only need a single location fix
        fusedLocationClient.removeLocationUpdates(locationCallback);
    }
};

2. Fix Potential Null Pointer Crashes

A common hidden issue here is accessing mMap before it's fully initialized. We added a null check for mMap in the callback to prevent this—always guard against null objects when dealing with map or location data.

3. Update Permission Handling Logic

Make sure your onRequestPermissionsResult triggers location updates right after permissions are granted:

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_LOCATION: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    mMap.setMyLocationEnabled(true);
                    startLocationUpdates(); // Start updates now that we have permission
                }
            } else {
                Toast.makeText(this, "Permission not given.", Toast.LENGTH_LONG).show();
            }
            return;
        }
    }
}

4. Clean Up Deprecated Code

Remove all GoogleApiClient related code (interfaces, buildGoogleApiClient, onConnected, etc.)—they're obsolete with the modern location client.

Final Tip

If you still run into issues, check Logcat for the exact crash stack trace. It will pinpoint exactly where the crash occurs (e.g., a null pointer or invalid API call) and help you resolve it quickly.

内容的提问来源于stack exchange,提问作者cristiano ronaldo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 11:42:44