Flutter后台定位插件flutter_background_geolocation的使用
Flutter后台定位插件flutter_background_geolocation的使用
简介
flutter_background_geolocation
是一个高度复杂的背景位置跟踪和地理围栏模块,具有节能的运动检测智能,适用于 iOS 和 Android。该插件的操作理念是利用设备的加速度计、陀螺仪和磁力计等传感器来检测设备是否处于移动或静止状态。
- 当设备被检测到正在移动时,插件将自动根据配置的距离过滤器(米)开始记录位置。
- 当设备被检测到处于静止状态时,插件会自动关闭位置服务以节省电量。
此外,此插件还有 Cordova、React Native、NativeScript 和纯原生版本可用。
注意:Android 模块需要购买许可证,但在 DEBUG 构建中可以正常使用。对于 RELEASE 构建,则必须购买许可证才能使用。
安装插件
1. 在 pubspec.yaml
中添加依赖项
dependencies:
flutter_background_geolocation: '^4.12.0'
或者从 Git 获取最新版本:
dependencies:
flutter_background_geolocation:
git:
url: https://github.com/transistorsoft/flutter_background_geolocation.git
2. 配置设置指南
使用插件
首先,导入包并命名空间以避免类名冲突:
import 'package:flutter_background_geolocation/flutter_background_geolocation.dart' as bg;
接下来,按照以下三个步骤使用 BackgroundGeolocation
:
- 注册事件监听器
- 配置插件
- 启动插件
示例代码
下面是一个完整的示例,展示了如何在应用程序中使用 flutter_background_geolocation
插件:
import 'package:flutter/material.dart';
import 'package:flutter_background_geolocation/flutter_background_geolocation.dart' as bg;
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
void initState() {
super.initState();
// 1. 注册事件监听器
bg.BackgroundGeolocation.onLocation((bg.Location location) {
print('[location] - $location');
});
bg.BackgroundGeolocation.onMotionChange((bg.Location location) {
print('[motionchange] - $location');
});
bg.BackgroundGeolocation.onProviderChange((bg.ProviderChangeEvent event) {
print('[providerchange] - $event');
});
// 2. 配置插件
bg.BackgroundGeolocation.ready(bg.Config(
desiredAccuracy: bg.Config.DESIRED_ACCURACY_HIGH,
distanceFilter: 10.0,
stopOnTerminate: false,
startOnBoot: true,
debug: true,
logLevel: bg.Config.LOG_LEVEL_VERBOSE
)).then((bg.State state) {
if (!state.enabled) {
// 3. 启动插件
bg.BackgroundGeolocation.start();
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Background Geolocation Example'),
),
body: Center(
child: Text('Background Geolocation is running.'),
),
);
}
}
头部任务处理
为了处理应用不在前台运行时的事件,您还需要注册头部任务处理函数:
@pragma('vm:entry-point')
void backgroundGeolocationHeadlessTask(bg.HeadlessEvent headlessEvent) async {
print('📬 --> $headlessEvent');
switch (headlessEvent.name) {
case bg.Event.BOOT:
bg.State state = await bg.BackgroundGeolocation.state;
print("📬 didDeviceReboot: ${state.didDeviceReboot}");
break;
// 其他事件处理...
}
}
void main() {
WidgetsFlutterBinding.ensureInitialized();
// 注册 BackgroundGeolocation 头部任务
bg.BackgroundGeolocation.registerHeadlessTask(backgroundGeolocationHeadlessTask);
runApp(MyApp());
}
调试与测试
您可以参考官方提供的调试指南和测试服务器进行进一步的调试和性能分析:
通过这些资源,您可以更轻松地理解和优化您的应用程序的位置跟踪功能。
更多关于Flutter后台定位插件flutter_background_geolocation的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter后台定位插件flutter_background_geolocation的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,下面是一个关于如何使用 flutter_background_geolocation
插件的简要示例代码。这个插件允许你在 Flutter 应用中实现后台定位功能。
首先,确保你已经在 pubspec.yaml
文件中添加了 flutter_background_geolocation
依赖:
dependencies:
flutter:
sdk: flutter
flutter_background_geolocation: ^4.4.0 # 请检查最新版本号
然后运行 flutter pub get
来获取依赖。
接下来,配置 Android 和 iOS 的权限和设置。
Android 配置
在 android/app/src/main/AndroidManifest.xml
中添加必要的权限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />
并在 MainActivity.kt
或 MainActivity.java
中配置服务:
// MainActivity.kt
package com.example.yourapp
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import com.transistorsoft.flutter.backgroundgeolocation.BackgroundGeolocationPlugin
class MainActivity: FlutterActivity() {
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
BackgroundGeolocationPlugin.registerWith(flutterEngine.dartExecutor.binaryMessenger)
}
}
iOS 配置
在 ios/Runner/Info.plist
中添加必要的权限:
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>This app needs access to location when in use and in the background.</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>This app needs access to location even when closed or not in use.</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>This app needs access to location when open.</string>
<key>UIBackgroundModes</key>
<array>
<string>location</string>
</array>
并在 AppDelegate.swift
或 AppDelegate.m
中配置插件(如果使用 Swift):
// AppDelegate.swift
import UIKit
import Flutter
import flutter_background_geolocation
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
BackgroundGeolocationPlugin.register(with: registrar(forPlugin: "flutter_background_geolocation")!)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
Flutter 代码实现
在你的 Flutter 项目中,你可以使用如下代码来初始化并使用 flutter_background_geolocation
插件:
import 'package:flutter/material.dart';
import 'package:flutter_background_geolocation/flutter_background_geolocation.dart' as bg;
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
void initState() {
super.initState();
initBackgroundGeolocation();
}
void initBackgroundGeolocation() async {
bg.BackgroundGeolocation.ready(bg.Config(
desiredAccuracy: bg.Config.DESIRED_ACCURACY_HIGH,
distanceFilter: 10.0,
stopOnTerminate: false,
startOnBoot: true,
debug: true,
logLevel: bg.Config.LOG_LEVEL_VERBOSE,
enableHeadless: true,
foregroundService: true,
notification: bg.Notification(
title: "Location Tracking",
text: "enabled",
smallIcon: "drawable/ic_notification",
largeIcon: "drawable/ic_launcher",
priority: bg.Config.NOTIFICATION_PRIORITY_MIN,
sticky: true,
),
)).then((bg.State state) {
if (!state.enabled) {
bg.BackgroundGeolocation.start().then((bg.State state) {
print("[ready] ${state.toMap()}");
}).catchError((error) {
console.error("[ready] ERROR: ", error);
});
}
}).catchError((error) {
console.error("[ready] ERROR: ", error);
});
bg.BackgroundGeolocation.onLocation((bg.Location location) {
print("[location] -", location);
});
bg.BackgroundGeolocation.onMotionChange((bg.Location location) {
print("[motionchange] -", location);
});
bg.BackgroundGeolocation.onActivityChange((bg.ActivityChangeEvent event) {
print("[activitychange] -", event);
});
bg.BackgroundGeolocation.onHttp((bg.HttpEvent response) {
print("[http] -", response);
});
bg.BackgroundGeolocation.onError((bg.BackgroundGeolocationError error) {
print("[error] -", error);
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Flutter Background Geolocation'),
),
body: Center(
child: Text('Check console for logs'),
),
),
);
}
}
上述代码展示了如何初始化 flutter_background_geolocation
插件,并监听位置变化、运动状态变化、活动状态变化以及 HTTP 响应和错误。你可以根据具体需求进一步自定义这些监听器和配置。
请确保在实际应用中处理所有可能的错误和边界情况,并根据应用需求调整配置。