当应用程序进入后台时,位置跟踪将停止。有什么解决办法吗?

问题描述 投票:0回答:1

我们的 flutter 应用程序是工作门户应用程序,用户可以在其中确认零工,机构可以在其中发布工作。现在我们要添加实时定位功能,该功能将在轮班开始前 1 小时跟踪用户的实时位置。

我正在尝试不同的技术。对于应用程序终止状态,我找到了警报包,它会在应用程序被终止时安排向应用程序发出通知,并使应用程序再次处于活动状态。

对此有什么建议吗?当应用程序处于前台和后台时,如何持续跟踪用户位置?

这是我用来在示例应用程序上测试该功能的代码

import 'dart:async';
import 'dart:developer';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:get/get_navigation/get_navigation.dart';

import 'package:location/location.dart' as l;
import 'package:permission_handler/permission_handler.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const GetMaterialApp(
      themeMode: ThemeMode.dark,
      debugShowCheckedModeBanner: false,
      home: HomeScreen(),
    );
  }
}

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  bool gpsEnabled = false;
  bool permissionGranted = false;
  l.Location location = l.Location();
  late StreamSubscription subscription;
  bool trackingEnabled = false;

  List<l.LocationData> locations = [];

  @override
  void initState() {
    super.initState();
    checkStatus();
  }

  @override
  void dispose() {
    stopTracking();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Location App'),
        centerTitle: true,
      ),
      body: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 12),
        child: Column(
          mainAxisSize: MainAxisSize.max,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            buildListTile(
              "GPS",
              gpsEnabled
                  ? const Text("Okey")
                  : ElevatedButton(
                  onPressed: () {
                    requestEnableGps();
                  },
                  child: const Text("Enable Gps")),
            ),
            buildListTile(
              "Permission",
              permissionGranted
                  ? const Text("Okey")
                  : ElevatedButton(
                  onPressed: () {
                    requestLocationPermission();
                  },
                  child: const Text("Request Permission")),
            ),
            buildListTile(
              "Location",
              trackingEnabled
                  ? ElevatedButton(
                  onPressed: () {
                    stopTracking();
                  },
                  child: const Text("Stop"))
                  : ElevatedButton(
                  onPressed: gpsEnabled && permissionGranted
                      ? () {
                    startTracking();
                  }
                      : null,
                  child: const Text("Start")),
            ),
            ElevatedButton(
              onPressed: clearFirestoreDatabase,
              child: const Text("Clear Firestore Database"),
            ),
            Expanded(
                child: ListView.builder(
                  itemCount: locations.length,
                  itemBuilder: (context, index) {
                    return ListTile(
                      title: Text(
                          "${locations[index].latitude} ${locations[index].longitude}"),
                    );
                  },
                ))
          ],
        ),
      ),
    );
  }

  ListTile buildListTile(
      String title,
      Widget? trailing,
      ) {
    return ListTile(
      dense: true,
      title: Text(title),
      trailing: trailing,
    );
  }

  void requestEnableGps() async {
    if (gpsEnabled) {
      log("Already open");
    } else {
      bool isGpsActive = await location.requestService();
      if (!isGpsActive) {
        setState(() {
          gpsEnabled = false;
        });
        log("User did not turn on GPS");
      } else {
        log("gave permission to the user and opened it");
        setState(() {
          gpsEnabled = true;
        });

      }
    }
  }

  void requestLocationPermission() async {
    PermissionStatus permissionStatus =
    await Permission.locationWhenInUse.request();
    if (permissionStatus == PermissionStatus.granted) {
      setState(() {
        permissionGranted = true;
      });
    } else {
      setState(() {
        permissionGranted = false;
      });
    }
  }

  Future<bool> isPermissionGranted() async {
    return await Permission.locationWhenInUse.isGranted;
  }

  Future<bool> isGpsEnabled() async {
    return await Permission.location.serviceStatus.isEnabled;
  }

  checkStatus() async {
    bool _permissionGranted = await isPermissionGranted();
    bool _gpsEnabled = await isGpsEnabled();
    setState(() {
      permissionGranted = _permissionGranted;
      gpsEnabled = _gpsEnabled;
    });
  }

  addLocation(l.LocationData data) {
    setState(() {
      locations.insert(0, data);
    });
  }

  clearLocation() {
    setState(() {
      locations.clear();
    });
  }

  Future<void> addLocationToFirestore(l.LocationData locationData) async {
    try {
      await FirebaseFirestore.instance.collection('locations').add({
        'latitude': locationData.latitude,
        'longitude': locationData.longitude,
      });
      log("Location added to Firestore: ${locationData.latitude}, ${locationData.longitude}");
    } catch (e) {
      log("Failed to add location: $e");
    }
  }

  Future<void> clearFirestoreDatabase() async {
    try {
      CollectionReference locations =
      FirebaseFirestore.instance.collection('locations');

      // Get all documents in the "locations" collection
      QuerySnapshot querySnapshot = await locations.get();

      // Delete each document in the collection
      for (QueryDocumentSnapshot doc in querySnapshot.docs) {
        await doc.reference.delete();
        log("Document with ID ${doc.id} deleted");
      }

      log("Firestore database cleared successfully.");
    } catch (e) {
      log("Failed to clear Firestore database: $e");
    }
  }

  void startTracking() async {
    if (!(await isGpsEnabled())) {
      return;
    }
    if (!(await isPermissionGranted())) {
      return;
    }
    subscription = location.onLocationChanged.listen((event) {
      addLocation(event);
      addLocationToFirestore(event); // Save to Firestore
      log('Location update: ${event.latitude}, ${event.longitude}');
    });
    setState(() {
      trackingEnabled = true;
    });
  }



  void stopTracking() {
    subscription.cancel();
    setState(() {
      trackingEnabled = false;
    });
    clearLocation();
  }
}

这里讨论的技术在应用程序打开时成功获取并更新数据库中的用户位置坐标(纬度,经度)。但是当应用程序进入后台时,位置更新发送到数据库就会停止。

flutter dart google-cloud-firestore location tracking
1个回答
0
投票

我认为你应该使用 flutter_background_service 包。这是我在应用程序中使用的唯一包。它使用通知在后台工作。如果您的应用程序被杀死或在后台运行,它可以正常工作。 包链接:[1]:https://pub.dev/packages/flutter_background_service

© www.soinside.com 2019 - 2024. All rights reserved.