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

Android后台服务中Fused Location API的OnLocationResult仅触发一次求助

Hey Maximus, let's break down your problem step by step—you're right about part of it, but there are a few other key reasons your onLocationResult() stops firing after the first update. Here's what you need to check and fix:

First, your core question: Yes, but...

onLocationResult() does trigger primarily when the device's location changes enough to meet the criteria you set in your LocationRequest. But if it's not firing even when you know the device is moving, there are other critical issues to address.

1. Double-check your LocationRequest parameters

The settings you define here directly control how often updates are sent:

  • setSmallestDisplacement(float meters): If you set this to a high value (like 100m), the API won't send updates until the device moves that far. Try lowering it (e.g., 10m) for testing.
  • setInterval(long millis) and setFastestInterval(long millis): These set the desired and maximum update frequency. If your interval is too long (e.g., 30 minutes), you won't get updates often.
  • setPriority(int): Using PRIORITY_LOW_POWER or PRIORITY_BALANCED_POWER_ACCURACY can reduce update frequency to save battery. For consistent background updates, you might need PRIORITY_HIGH_ACCURACY (but note this uses more power).

2. Background service survival (Nougat+ restrictions)

Even if you've done basic adaptation, Android 8.0+ has strict limits on background services—they can be killed by the system to free resources. To keep your location service running reliably:

  • Use a foreground service: This requires showing a persistent notification (which tells the user your app is actively tracking location), and it gives your service higher priority so it's less likely to be terminated.

Here's a quick snippet to implement this in your service:

// In onCreate() for Android O+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    NotificationChannel channel = new NotificationChannel(
        "location_tracker", 
        "Background Location", 
        NotificationManager.IMPORTANCE_LOW
    );
    NotificationManager notificationManager = getSystemService(NotificationManager.class);
    notificationManager.createNotificationChannel(channel);
}

// Build the foreground notification
Notification notification = new NotificationCompat.Builder(this, "location_tracker")
    .setSmallIcon(R.drawable.ic_location)
    .setContentTitle("Location Service Active")
    .setContentText("Tracking your location in background")
    .setPriority(NotificationCompat.PRIORITY_LOW)
    .build();

// Start foreground service
startForeground(101, notification);

3. Permissions (don't overlook Android 10+ requirements)

You mentioned adapting for Marshmallow/Nougat, but Android 10 (API 29) introduced the ACCESS_BACKGROUND_LOCATION permission. If your app targets API 29+, you need to request this permission in addition to ACCESS_FINE_LOCATION/ACCESS_COARSE_LOCATION to get location updates while in the background.

Make sure you:

  • Declare the permission in your AndroidManifest.xml:
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
    
  • Request it from the user at runtime (along with the foreground location permission).

4. Ensure your callback is re-registered if the service restarts

If your service is killed and restarted by the system, onCreate() only runs once—so if you only request location updates in onCreate(), the callback won't be re-registered after a restart.

Move your location update request to onStartCommand() instead, and return START_STICKY to tell the system to restart your service if it's terminated:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // Re-request location updates every time the service starts
    requestLocationUpdates();
    return START_STICKY;
}

private void requestLocationUpdates() {
    LocationRequest locationRequest = LocationRequest.create();
    locationRequest.setInterval(10000); // 10 seconds
    locationRequest.setFastestInterval(5000); // 5 seconds max
    locationRequest.setSmallestDisplacement(10); // 10 meters
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper());
    }
}

Final Checks

  • Make sure you're not accidentally calling removeLocationUpdates(locationCallback) somewhere in your code (this would stop all future updates).
  • Test with the device's GPS enabled (if using high accuracy mode) and move around to trigger location changes.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:11:16