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

Flutter如何在安卓/iOS应用关闭时实现15秒级定位?

Flutter应用关闭后高频位置追踪实现问题

我正在开发一款Flutter应用,需要在应用关闭时以15-30秒的频率获取用户位置。目前使用location Flutter包仅能在应用处于后台(未完全关闭)时获取位置,但我希望实现应用关闭后及开机时的位置追踪。

我曾尝试使用geolocator和workmanager获取位置,但它们的最小间隔为15分钟,频率过低。当前使用的location包在应用关闭后停止运行,且无法开机自启。我了解到flutter_background_geolocation,但它并非开源。


现有实现代码

1. Android原生位置服务(LocationService.kt)

文件路径:myapp/android/app/main/java/com/flutter/myapp/LocationService.kt

package com.flutter.myapp

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat
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.location.FusedLocationProviderClient
class LocationService : Service() {
    private val CHANNEL_ID = "ForegroundServiceChannel"
    private lateinit var fusedLocationClient: FusedLocationProviderClient
    private lateinit var locationCallback: LocationCallback

    override fun onCreate() {
        super.onCreate()
        createNotificationChannel()

        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)

        locationCallback = object : LocationCallback() {
            override fun onLocationResult(locationResult: LocationResult) {
                super.onLocationResult(locationResult)
                locationResult?.let {
                    // Handle location update here
                    val location = it.lastLocation
            }
        }
        startLocationUpdates()
    }
    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val serviceChannel = NotificationChannel(
                CHANNEL_ID,
                "Foreground Service Channel",
                NotificationManager.IMPORTANCE_DEFAULT
            )
            val manager = getSystemService(NotificationManager::class.java)
            manager.createNotificationChannel(serviceChannel)
        }
    }

    private fun startLocationUpdates() {
        val locationRequest = LocationRequest.create().apply {
            interval = 15000 
            fastestInterval = 5000
            priority = LocationRequest.PRIORITY_HIGH_ACCURACY
        }

        fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null)
    }
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val notification: Notification = NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("Location Service")
            .setContentText("Tracking your location...")
            .setContentIntent(getPendingIntent())
            .build()

        startForeground(1, notification)
        return START_STICKY
    }
    private fun getPendingIntent(): PendingIntent {
        val notificationIntent = Intent(this, MainActivity::class.java)
        return PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE)
    }
    override fun onBind(intent: Intent?): IBinder? {
        return null
    }
    override fun onDestroy() {
        super.onDestroy()
        fusedLocationClient.removeLocationUpdates(locationCallback)
    }
}

2. AndroidManifest服务配置

添加到myapp/android/app/main/kotlin/com/flutter/myapp/目录下的Manifest文件中:

<service
        android:name=".LocationService"
        android:enabled="true"
        android:exported="false"/>

3. Flutter端服务调用代码

class ForegroundService {
  static const platform =
      MethodChannel('com.flutter.myapp/locationService');

  Future<void> startService() async {
    try {
      final intent = AndroidIntent(
        action: 'com.flutter.myapp.START_LOCATION_SERVICE',
        package: 'com.flutter.myapp',
        componentName: 'com.flutter.myapp/.LocationService',
        flags: <int>[Flag.FLAG_ACTIVITY_NEW_TASK],
      ); 
      intent.sendBroadcast();
      await platform.invokeMethod('startService');
    } on PlatformException catch (e) {
      print("Failed to start service: '${e.message}'.");
    }
  }

  Future<void> stopService() async {
    try {
      await platform.invokeMethod('stopService');
    } on PlatformException catch (e) {
      print("Failed to stop service: '${e.message}'.");
    }
  }
}

应用关闭时的日志输出

D/FlutterGeolocator(27222): Detaching Geolocator from activity
D/FlutterGeolocator(27222): Flutter engine disconnected. Connected engine count 0
D/FlutterGeolocator(27222): Disposing Geolocator services
E/FlutterGeolocator(27222): Geolocator position updates stopped
D/FlutterGeolocator(27222): Stopping location service.
D/FlutterLocationService(27222): Unbinding from location service.
D/FlutterLocationService(27222): Destroying service.
D/FlutterGeolocator(27222): Unbinding from location service.
D/FlutterGeolocator(27222): Destroying location service.
D/FlutterGeolocator(27222): Stopping location service.
D/FlutterGeolocator(27222): Destroyed location service.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 05:27:03