Flutter后台定位插件bg_location的使用
Flutter后台定位插件bg_location的使用
bg_location
插件通过显著变化位置服务(Significant-Change Location Service)实现了后台定位功能(仅适用于 iOS)。该插件允许应用程序在后台持续接收设备的位置更新。
使用说明
依赖安装
在 pubspec.yaml
文件中添加以下依赖:
dependencies:
bg_location: ^0.0.1
运行 flutter pub get
安装依赖。
初始化与基本使用
以下是一个完整的示例代码,展示如何使用 bg_location
插件实现后台定位功能。
示例代码
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:bg_location/bg_location.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _platformVersion = 'Unknown';
@override
void initState() {
super.initState();
_initPlatform();
}
// 初始化平台版本信息
Future<void> _initPlatform() async {
String platformVersion;
try {
platformVersion = await BgLocation.platformVersion ?? 'Unknown platform version';
} on PlatformException {
platformVersion = 'Failed to get platform version.';
}
if (!mounted) return;
setState(() {
_platformVersion = platformVersion;
});
}
// 开始后台定位
Future<void> _startTracking() async {
// 注册位置更新回调
BgLocation.getLocationUpdates((location) => print('[my sample app] Location update received: $location'));
// 启动后台定位服务
await BgLocation.startTracking();
}
// 停止后台定位
Future<void> _stopTracking() async {
await BgLocation.stopTracking();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('bg_location 示例'),
),
body: Center(
child: Text('运行环境: $_platformVersion\n'),
),
floatingActionButton: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// 查看平台版本
FloatingActionButton.extended(
onPressed: _initPlatform,
label: Text("获取平台版本"),
icon: Icon(Icons.settings),
),
SizedBox(width: 10), // 添加间距
// 开始后台定位
FloatingActionButton.extended(
onPressed: _startTracking,
label: Text("开始定位"),
icon: Icon(Icons.play_arrow),
),
SizedBox(width: 10), // 添加间距
// 停止后台定位
FloatingActionButton.extended(
onPressed: _stopTracking,
label: Text("停止定位"),
icon: Icon(Icons.stop),
),
],
),
),
);
}
}
代码详解
-
初始化平台版本
_initPlatform()
方法用于获取当前平台的版本信息,并通过setState()
更新 UI。- 如果发生异常(如无法获取版本信息),则返回默认值
'Unknown platform version'
。
-
注册位置更新回调
- 使用
BgLocation.getLocationUpdates()
方法注册一个回调函数,当设备位置发生变化时,会触发回调并打印位置信息。
- 使用
-
启动后台定位
- 调用
BgLocation.startTracking()
启动后台定位服务。此时,设备会在后台持续接收位置更新。
- 调用
-
停止后台定位
- 调用
BgLocation.stopTracking()
停止后台定位服务,释放相关资源。
- 调用
运行效果
运行上述代码后,点击按钮可以完成以下操作:
- 点击“获取平台版本”按钮:查看当前平台版本。
- 点击“开始定位”按钮:启动后台定位服务,开始接收位置更新。
- 点击“停止定位”按钮:停止后台定位服务。
注意事项
-
仅支持 iOS
- 该插件目前仅支持 iOS 平台,Android 平台尚未实现。
-
权限配置
- 在 iOS 中,确保在
Info.plist
文件中添加以下权限声明:<key>NSLocationWhenInUseUsageDescription</key> <string>我们需要您的位置信息以提供更好的服务。</string> <key>NSLocationAlwaysUsageDescription</key> <string>我们需要始终访问您的位置信息。</string>
- 在 iOS 中,确保在
更多关于Flutter后台定位插件bg_location的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter后台定位插件bg_location的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
bg_location
是一个用于在 Flutter 应用中实现后台定位的插件。它允许应用在后台持续获取设备的位置信息,即使应用不在前台运行。这对于需要持续跟踪用户位置的应用(如健身应用、导航应用等)非常有用。
安装 bg_location
插件
首先,你需要在 pubspec.yaml
文件中添加 bg_location
插件的依赖:
dependencies:
flutter:
sdk: flutter
bg_location: ^2.0.0 # 请检查最新版本
然后运行 flutter pub get
来安装插件。
配置 Android 和 iOS
Android 配置
-
权限配置:在
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" />
-
后台服务配置:在
AndroidManifest.xml
文件中添加以下服务声明:<service android:name="com.rekab.app.background_locator.IsolateHolderService" android:foregroundServiceType="location" />
-
ProGuard 配置(如果需要):如果你启用了 ProGuard,请在
proguard-rules.pro
文件中添加以下规则:-keep class com.rekab.app.background_locator.** { *; }
iOS 配置
-
权限配置:在
Info.plist
文件中添加以下键值对以请求定位权限:<key>NSLocationAlwaysAndWhenInUseUsageDescription</key> <string>我们需要您的位置信息来提供更好的服务。</string> <key>NSLocationWhenInUseUsageDescription</key> <string>我们需要您的位置信息来提供更好的服务。</string>
-
后台模式配置:在
Info.plist
文件中启用后台定位模式:<key>UIBackgroundModes</key> <array> <string>location</string> </array>
使用 bg_location
插件
初始化插件
在 main.dart
文件中初始化 bg_location
插件:
import 'package:bg_location/bg_location.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await BgLocation.initialize();
runApp(MyApp());
}
启动后台定位服务
你可以使用 BgLocation.start()
方法来启动后台定位服务:
await BgLocation.start();
停止后台定位服务
你可以使用 BgLocation.stop()
方法来停止后台定位服务:
await BgLocation.stop();
监听位置更新
你可以通过 BgLocation.onLocationUpdate
来监听位置更新:
BgLocation.onLocationUpdate.listen((LocationDto location) {
print('Latitude: ${location.latitude}, Longitude: ${location.longitude}');
});
处理后台任务
bg_location
插件使用 Dart 的 Isolate
来处理后台任务。你可以在 callbackDispatcher
中定义后台任务的逻辑:
void callbackDispatcher() {
BgLocation.setupIsolate();
BgLocation.onLocationUpdate.listen((LocationDto location) {
// 处理位置更新
print('Background Location: ${location.latitude}, ${location.longitude}');
});
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await BgLocation.initialize(callbackDispatcher);
runApp(MyApp());
}
示例代码
以下是一个完整的示例代码,展示了如何使用 bg_location
插件:
import 'package:flutter/material.dart';
import 'package:bg_location/bg_location.dart';
void callbackDispatcher() {
BgLocation.setupIsolate();
BgLocation.onLocationUpdate.listen((LocationDto location) {
print('Background Location: ${location.latitude}, ${location.longitude}');
});
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await BgLocation.initialize(callbackDispatcher);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Background Location Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: () async {
await BgLocation.start();
print('Background location started');
},
child: Text('Start Background Location'),
),
ElevatedButton(
onPressed: () async {
await BgLocation.stop();
print('Background location stopped');
},
child: Text('Stop Background Location'),
),
],
),
),
),
);
}
}