搜索插件、代码仓与 APP 分类

插件详情v1.5.1

native_geofence

使用原生 iOS 和 Android API 的电池高效 Flutter 地理围栏。

AndroidiOS
近 30 天下载
2万
喜欢数
45
Pub 分数
160

安装插件

flutter pub add native_geofence

插件介绍

基于插件公开信息、社区数据与项目使用情况整理的选型参考。

原生地理围栏是一个电池高效的 Flutter 插件,利用原生 iOS 和 Android API 提供精确的位置触发功能。它使应用程序能够以最低的功耗监控预设地理区域的进入和退出事件。该插件可无缝集成到 Flutter 项目中,并支持后台执行,非常适合实时位置服务。通过最少的设置和可靠的性能,确保在各种设备上保持一致的地理围栏行为。

适合场景

  • 实时位置警报
  • 基于位置的提醒
  • 资产追踪
  • 地理围栏通知
  • 背景监控

主要特点

  • 使用原生平台 API
  • 低电池消耗
  • 后台执行支持
  • 跨平台兼容性
  • 简单的事件驱动 API

适合对象

  • 需要高效地理围栏的应用程序
  • 位置感知应用
  • 现场服务管理工具
  • 零售近距离营销
  • 物流与配送跟踪

使用建议

  • 需要位置权限
  • 后台执行可能因设备而异
  • 限于 Android 和 iOS
  • 用户必须启用位置服务
  • 精度取决于设备硬件

原始 README

以下为关联源码仓库的 README 原文快照,最新内容请访问源码仓库。

Native Geofence

Battery efficient Flutter geofencing plugin that uses native iOS and Android APIs.

What is geofencing?
A way for your app to be alerted when the user enters or exits a geographical region. You might use geofences to perform location-related tasks. For example, to setup reminders when the user leaves their house.
What are the plugin requirements?
iOS 14+ and Android API 23+. You will also need to obtain background location permission from the user.

Features

  • Uses CLLocationManager on iOS and GeofencingClient on Android
  • Create geofences
  • Be notified of enter/exit/dwell events
  • Works when the application is:
    • In the foreground
    • In the background
    • Terminated
  • Geofences are re-registered after device reboot
  • Fetch currently registered geofences
  • [Android] Run foreground service to handle geofence event

Setup

Android
Android
  1. Kotlin setup

This plugin works with both Android Kotlin setups, so follow the one that matches your toolchain:

  • Flutter 3.44+ (AGP 9) — built-in Kotlin: Kotlin is provided by the Android Gradle Plugin, so there is nothing to add. Do not apply the kotlin-android Gradle plugin yourself — AGP 9 rejects an explicitly applied Kotlin plugin. See Flutter's built-in Kotlin migration guide.
  • Older Flutter (AGP 8): apply the Kotlin Gradle plugin as usual, and ensure your Kotlin version is at least 1.9.25 (see this guide). The latest Kotlin version can be found here.

The example app demonstrates the AGP 8 setup, with comments in its Gradle files noting the AGP 9 difference.

NOTE: You may also need Gradle 8+ to use this plugin. See this issue.

  1. Set your minSdkVersion to 23 or above.

Explanation: If you need to support prior Android builds it might be possible to accommodate this. Please send a PR or file a bug.

See the example plugin for a full demonstration.

  1. In your AndroidManifest.xml add the following lines right before </application>:
<!-- Used by plugin: native_geofence -->
<receiver android:name="com.chunkytofustudios.native_geofence.receivers.NativeGeofenceBroadcastReceiver"
          android:exported="true"/>
<receiver android:name="com.chunkytofustudios.native_geofence.receivers.NativeGeofenceRebootBroadcastReceiver"
          android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"></action>
    </intent-filter>
</receiver>
<service android:name="com.chunkytofustudios.native_geofence.NativeGeofenceForegroundService"
          android:permission="android.permission.BIND_JOB_SERVICE" android:exported="true"/>

Explanation: The NativeGeofenceBroadcastReceiver is used to listen for geofence events the Android OS sends. The NativeGeofenceRebootBroadcastReceiver runs after device reboot and re-registers geofences (this is required since Android doesn't retain them). Finally, NativeGeofenceForegroundService is utilized when you want to run a foreground service when handling a geofence callback.

  1. In the same file declare the neccesary permissions before the <application ... line:
<!-- Used by plugin: native_geofence -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>

Explanation: The coarse and fine locations are required to create a geofence. The background location permission is also required for geofence creation on Android API level 29+. The boot completed permission is required to re-register geofences after reboot. The wake lock permission is only required if you need to run foreground services to respond to geofence events.

  1. Optional: Disable battery optimization

If you want to perform any heavy work when a Geofence triggers (within the Geofence callback), such as calling a backend API, you will need to ask the user to disable battery optimization for your app.

You can do so by using the disable_battery_optimization package. You can find a code sample here.

iOS
iOS
  1. Migrate your app to Swift

If your app is using Objective-C you will need to migrate to Swift. Here is a guide you can follow.

  1. In your Info.plist add the following key-value pairs:
<key>NSLocationWhenInUseUsageDescription</key>
<string>USER_VISIBLE_STRING__DESCRIBE_HOW_YOUR_APP_USES_LOCATION.</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>USER_VISIBLE_STRING__DESCRIBE_HOW_YOUR_APP_USES_BACKGROUND_LOCATION.</string>

Explanation: The in-use location permission is required to create geofences. The always location permission is required if you want to be notified of geofence events when your app isn't running.

  1. Update your AppDelegate to call NativeGeofencePlugin:
Swift
Swift

In your AppDelegate.swift file import the plugin:

import native_geofence

and add the following near the top of the application function:

// Used by plugin: native_geofence
NativeGeofencePlugin.setPluginRegistrantCallback { registry in
    GeneratedPluginRegistrant.register(with: registry)
}
Objective-C
Objective-C

In your AppDelegate.m file import the plugin and define the registerPlugins function:

#import <native_geofence/NativeGofencePlugin.h>

void registerPlugins(NSObject<FlutterPluginRegistry>* registry) {
  [GeneratedPluginRegistrant registerWithRegistry:registry];
}

and add the following within the application(_:didFinishLaunchingWithOptions:) function:

// Used by plugin: native_geofence
[NativeGofencePlugin setPluginRegistrantCallback:registerPlugins];

  1. Set your iOS version to 14.0 or above.

You can do so in your Podfile by adding the line platform :ios, '14.0'.

Explanation: If you need to support prior iOS builds it might be possible to accommodate this. Please send a PR or file a bug.

See the example plugin for a full demonstration.

Usage

Initialize the plugin

Before accesing any methods ensure you initialize the plugin:

await NativeGeofenceManager.instance.initialize();
Obtain permissions

This plugin does not deal with obtaining permissions from the user. Please use a 3rd party plugin, such as permission_handler for that.

As noted in the setup section you will need to obtain the following permissions:

  • Permission.location
  • Permission.locationAlways: if you want to be notified of geofence events when your app isn't running
Create geofence

First, define your geofence parameters using the Geofence class, for example:

Note: The ID must be unqiue. Please see the API reference for details.

final zone1 = Geofence(
  id: 'zone1',
  location: Location(latitude: 40.75798, longitude: -73.98554), // Times Square
  radiusMeters: 500,
  triggers: {
    GeofenceEvent.enter,
    GeofenceEvent.exit,
    GeofenceEvent.dwell,
  },
  iosSettings: IosGeofenceSettings(
    initialTrigger: true,
  ),
  androidSettings: AndroidGeofenceSettings(
    initialTriggers: {GeofenceEvent.enter},
    expiration: const Duration(days: 7),
    loiteringDelay: const Duration(minutes: 5),
    notificationResponsiveness: const Duration(minutes: 5),
  ),
);

Next, create a top-level function that has the @pragma('vm:entry-point') annotation; this will act as your geofence callback/handler:

Note: You can (optional) specify a unique callback function for each geofence.

@pragma('vm:entry-point')
Future<void> geofenceTriggered(GeofenceCallbackParams params) async {
  debugPrint('Geofence triggered with params: $params');
}

Finally, create the geofence:

await NativeGeofenceManager.instance.createGeofence(zone1, geofenceTriggered);
[Android only] Foreground work

If you need to access certain APIs or run a long job in your geofence callback you can promote the runner to a foreground service. You have access to the following functions when running within a geofence callback:

NativeGeofenceBackgroundManager.instance.promoteToForeground();
// Do a lot of work or access live location?
NativeGeofenceBackgroundManager.instance.demoteToBackground();

Note: Most tasks that complete in a few seconds, such as sending a notification, don't require your callback to run in a foreground service.

Warning: This functionality is not well tested. Please report any bugs you find.

Get registered geofences

You can see which geofences are currently active using:

final List<ActiveGeofence> myGeofences = await NativeGeofenceManager.instance.getRegisteredGeofences();
print('There are ${myGeofences.length} active geofences.')
Remove geofence

You have multiple options to stop listenning for geofence events:

// Remove a single geofence:
await NativeGeofenceManager.instance.removeGeofenceById('zone1');
// Remove all geofences:
await NativeGeofenceManager.instance.removeAllGeofences();

Error handling

All errors thrown by this plugin are wrapped in NativeGeofenceException.

Each exception will contain an error code, please see the API reference a description of each of them.

Ensure you catch this exception and take the neccesary action. For example you might:

try {
  await NativeGeofenceManager.instance.createGeofence(zone1, geofenceTriggered);
} on NativeGeofenceException catch (e) {
  if (e.code == NativeGeofenceErrorCode.missingLocationPermission) {
    print('Did the user grant us the location permission yet?')
    return
  }
  if (e.code == NativeGeofenceErrorCode.pluginInternal) {
    print('Some internal error occured: message=${e.message}, detail=${e.details}, stackTrace=${e.stacktrace}')
    return
  }
  // Handle other cases.
}

Example

The provided example app demonstrates how to request permissions, register geofences, and send notifications when geofence events occur.

Prior art

This plugin is based off of bkonyi/FlutterGeofencing and uses code snippets from flutter_workmanager. It was inspired by 525k.io's geofence_foreground_service plugin.

Contributing

Please file any issues, bugs, or feature requests at GitHub.

Pull requests are welcome.

Future work
  • Android: Allow customizing the notification shown when a geofence callback upgrades to a foreground service.
  • Android: Allow customizing the wake lock duration when foreground service is launched.
  • Other ideas?

Known Issues

  • iOS: After reboot, the first geofence event is triggered twice, one immediatly after the other. We recommend checking the last trigger time of a geofence in your app to discard duplicates.
  • Android: The emulator does not trigger geofence events if there are no apps accessing the device location. This is an emulator issue. As a workaround you can open Google Maps to get a location fix which will in turn trigger the geofence.

Author

This plugin is developed by Chunky Tofu Studios.

You can support us by checking out our apps!

For commercial support please reach out to hello@chunkytofustudios.com.

所属分类

依赖

依赖清单 2 项

  • meta^1.17.0
  • plugin_platform_interface^2.1.8

源码仓库

使用此插件的项目

暂无相关数据。