Flutter后台定位并集成Firebase插件background_geolocation_firebase的使用
Flutter后台定位并集成Firebase插件 background_geolocation_firebase
的使用
简介
background_geolocation_firebase
是一个用于 Flutter 的插件,可以将后台定位数据自动发送到你的 Firebase Firestore 数据库。该插件覆盖了 flutter_background_geolocation
插件的 SQLite 和 HTTP 服务。
许可证
Android 模块需要购买许可证才能在发布版本中使用。但是,它可以在 DEBUG 构建中免费使用。更多详细信息请参阅 官方文档。
目录
📚 API 文档
🔷 安装插件
在 pubspec.yaml
中添加依赖
dependencies:
background_geolocation_firebase: '^0.1.0'
或者从 Git 获取最新版本:
dependencies:
background_geolocation_firebase:
git:
url: https://github.com/transistorsoft/flutter_background_geolocation_firebase
🔷 配置指南
🔷 示例
以下是一个简单的示例,展示了如何在 Flutter 应用中使用 background_geolocation_firebase
插件。
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:background_geolocation_firebase/background_geolocation_firebase.dart';
import 'package:flutter_background_geolocation/flutter_background_geolocation.dart' as bg;
void main() {
runApp(new MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
void initState() {
super.initState();
initPlatformState();
}
// 平台消息是异步的,因此我们在异步方法中初始化。
Future<void> initPlatformState() async {
// 1. 首先配置 Firebase 适配器。
BackgroundGeolocationFirebase.configure(BackgroundGeolocationFirebaseConfig(
locationsCollection: "locations",
geofencesCollection: "geofences",
updateSingleDocument: false
));
// 2. 按照常规配置 BackgroundGeolocation。
bg.BackgroundGeolocation.onLocation((bg.Location location) {
print('[location] $location');
});
bg.BackgroundGeolocation.ready(bg.Config(
debug: true,
logLevel: bg.Config.LOG_LEVEL_VERBOSE,
stopOnTerminate: false,
startOnBoot: true
)).then((bg.State state) {
if (!state.enabled) {
bg.BackgroundGeolocation.start();
}
});
// 如果小部件在平台消息传输过程中被移除,我们希望丢弃回复而不是调用 setState 更新不存在的界面。
if (!mounted) return;
}
@override
Widget build(BuildContext context) {
return new MaterialApp(
home: new Scaffold(
appBar: new AppBar(
title: const Text('BGGeo Firebase Example', style: TextStyle(color: Colors.black)),
backgroundColor: Colors.amberAccent,
brightness: Brightness.light,
),
body: Text("BGGeo Firebase")
),
);
}
}
🔷 Firebase Functions
BackgroundGeolocation
将其 默认的位置数据模式 发送到你的 Firebase 应用。你可以实现自己的 Firebase Functions 来处理传入的数据。例如:
import * as functions from 'firebase-functions';
exports.createLocation = functions.firestore
.document('locations/{locationId}')
.onCreate((snap, context) => {
const record = snap.data();
const location = record.location;
console.log('[data] - ', record);
return snap.ref.set({
uuid: location.uuid,
timestamp: location.timestamp,
is_moving: location.is_moving,
latitude: location.coords.latitude,
longitude: location.coords.longitude,
speed: location.coords.speed,
heading: location.coords.heading,
altitude: location.coords.altitude,
event: location.event,
battery_is_charging: location.battery.is_charging,
battery_level: location.battery.level,
activity_type: location.activity.type,
activity_confidence: location.activity.confidence,
extras: location.extras
});
});
exports.createGeofence = functions.firestore
.document('geofences/{geofenceId}')
.onCreate((snap, context) => {
const record = snap.data();
const location = record.location;
console.log('[data] - ', record);
return snap.ref.set({
uuid: location.uuid,
identifier: location.geofence.identifier,
action: location.geofence.action,
timestamp: location.timestamp,
latitude: location.coords.latitude,
longitude: location.coords.longitude,
extras: location.extras,
});
});
🔷 配置选项
@param {String} locationsCollection [locations]
要发布 location
事件的集合名称。例如:
BackgroundGeolocationFirebase.configure(BackgroundGeolocationFirebaseConfig(
locationsCollection: '/locations'
));
BackgroundGeolocationFirebase.configure(BackgroundGeolocationFirebaseConfig(
locationsCollection: '/users/123/locations'
));
BackgroundGeolocationFirebase.configure(BackgroundGeolocationFirebaseConfig(
locationsCollection: '/users/123/routes/456/locations'
));
@param {String} geofencesCollection [geofences]
要发布 geofence
事件的集合名称。例如:
BackgroundGeolocationFirebase.configure(BackgroundGeolocationFirebaseConfig(
geofencesCollection: '/geofences'
));
BackgroundGeolocationFirebase.configure(BackgroundGeolocationFirebaseConfig(
geofencesCollection: '/users/123/geofences'
));
BackgroundGeolocationFirebase.configure(BackgroundGeolocationFirebaseConfig(
geofencesCollection: '/users/123/routes/456/geofences'
));
@param {Boolean} updateSingleDocument [false]
如果你希望插件更新 Firebase 中的单个文档而不是为每个 location
/ geofence
创建新文档,可以设置此选项。在这种情况下,你可能需要实现一个 Firebase 函数来处理单个文档的更新,并将位置存储在其他集合中。如果这是你的用例,还需要确保你的 locationsCollection
/ geofencesCollection
配置具有偶数个“部分”,形式为 /collection_name/document_id
,例如:
BackgroundGeolocationFirebase.configure(BackgroundGeolocationFirebaseConfig(
locationsCollection: '/locations/latest' // <-- 2 "parts": 偶数
));
// 或者
BackgroundGeolocationFirebase.configure(BackgroundGeolocationFirebaseConfig(
locationsCollection: '/users/123/routes/456/the_location' // <-- 4 "parts": 偶数
));
// 不要使用奇数个“部分”
BackgroundGeolocationFirebase.configure(BackgroundGeolocationFirebaseConfig(
locationsCollection: '/users/123/latest_location' // <-- 3 "parts": 奇数!不可以!
));
📚 Demo 应用程序
许可证
The MIT License (MIT)
Copyright © 2018 Chris Scott, Transistor Software
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
更多关于Flutter后台定位并集成Firebase插件background_geolocation_firebase的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter后台定位并集成Firebase插件background_geolocation_firebase的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter应用中实现后台定位并集成Firebase插件background_geolocation_firebase
,可以按照以下步骤进行。这是一个复杂的过程,涉及到配置Flutter项目、使用background_geolocation_firebase
插件、处理定位数据以及将数据上传到Firebase。以下是一个简化的代码示例,展示了如何实现这些功能。
1. 配置Flutter项目
首先,确保你的Flutter项目已经创建,并且已经添加了必要的依赖项。在pubspec.yaml
文件中添加background_geolocation_firebase
和Firebase相关的依赖项:
dependencies:
flutter:
sdk: flutter
background_geolocation_firebase: ^x.y.z # 替换为最新版本号
firebase_core: ^x.y.z # 替换为最新版本号
firebase_firestore: ^x.y.z # 替换为最新版本号
然后运行flutter pub get
来安装这些依赖项。
2. 配置Firebase
在Firebase控制台中创建一个新的Firebase项目,并添加Firestore数据库。然后,下载google-services.json
文件并将其放置在android/app/
目录下。对于iOS,需要将GoogleService-Info.plist
文件放置在ios/Runner/
目录下。
3. 初始化Firebase和Background Geolocation
在你的Flutter应用的主文件中(通常是main.dart
),初始化Firebase和Background Geolocation插件。
import 'package:flutter/material.dart';
import 'package:background_geolocation_firebase/background_geolocation_firebase.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_firestore/firebase_firestore.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
// 初始化Background Geolocation插件
BackgroundGeolocationFirebase.configure(
BackgroundGeolocationConfig(
desiredAccuracy: BackgroundGeolocationConfig.DESIRED_ACCURACY_HIGH,
distanceFilter: 10.0,
stopOnTerminate: false,
startOnBoot: true,
enableHeadless: true,
// 其他配置...
),
).then((LocationCallback locationCallback) {
locationCallback.onLocation((BackgroundLocation location) async {
// 处理定位数据
print('Latitude: ${location.latitude}, Longitude: ${location.longitude}');
// 将定位数据上传到Firebase Firestore
FirebaseFirestore.instance.collection('locations').add({
'latitude': location.latitude,
'longitude': location.longitude,
'timestamp': location.timestamp.toIso8601String(),
});
});
});
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Background Geolocation with Firebase'),
),
body: Center(
child: Text('Checking location in the background...'),
),
),
);
}
}
4. 处理后台任务(可选)
如果你的应用需要在后台执行长时间运行的任务(例如,持续定位),你可能需要实现一个headless服务。这通常涉及到创建一个Dart文件来处理这些后台任务。
创建一个新的Dart文件,例如background_geolocation_headless_task.dart
,并在其中实现headless回调:
import 'package:background_geolocation_firebase/background_geolocation_firebase.dart';
import 'package:firebase_firestore/firebase_firestore.dart';
void backgroundGeolocationHeadlessTask(BackgroundLocation location) async {
print('Headless Task: Latitude: ${location.latitude}, Longitude: ${location.longitude}');
// 将定位数据上传到Firebase Firestore
FirebaseFirestore.instance.collection('locations').add({
'latitude': location.latitude,
'longitude': location.longitude,
'timestamp': location.timestamp.toIso8601String(),
});
// 通知插件任务已完成
BackgroundGeolocationFirebase.finish();
}
然后,在你的main.dart
文件中注册这个headless任务:
import 'background_geolocation_headless_task.dart'; // 导入headless任务文件
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
// 注册headless任务
BackgroundGeolocationFirebase.registerHeadlessTask(backgroundGeolocationHeadlessTask);
// ...(其余代码保持不变)
}
注意事项
- 确保你已经正确配置了Firebase项目,并且已经启用了Firestore数据库。
- 在实际应用中,你可能需要添加更多的错误处理和日志记录。
- 后台定位可能会消耗更多的电量,因此应谨慎使用,并考虑用户的电池寿命。
这个示例提供了一个基本的框架,你可以根据自己的需求进行扩展和修改。