beacons 0.3.0

  • README.md
  • CHANGELOG.md
  • Example
  • Installing
  • Versions
  • 81

Beacons

pub package

Flutter plugin to work with beacons.
Supports Android API 16+ and iOS 8+.

Features:

  • Automatic permission management
  • Ranging
  • Monitoring (including background)

Supported beacons specifications:

  • iBeacon (iOS & Android)
  • Altbeacon (Android)

Installation

Add to pubspec.yaml:

dependencies:
  beacons: ^0.3.0

Note: The plugin is written in Swift for iOS.
There is a known issue for integrating swift plugin into Flutter project using the Objective-C template. Follow the instructions from Flutter#16049 to resolve the issue (Cocoapods 1.5+ is mandatory).

Setup specific for Android

Create a subclass of FlutterApplication:

class App : FlutterApplication() {

    override fun onCreate() {
        super.onCreate()

        // Beacons setup for Android
        BeaconsPlugin.init(this, object : BeaconsPlugin.BackgroundMonitoringCallback {
            override fun onBackgroundMonitoringEvent(event: BackgroundMonitoringEvent): Boolean {
                val intent = Intent(this@App, MainActivity::class.java)
                startActivity(intent)
                return true
            }
        })
    }
}

And register it in android/app/src/main/AndroidManifest.xml:

<manifest ...>
  ...
  <application
    android:name=".App"
    android:label="beacons_example"
    android:icon="@mipmap/ic_launcher">
    ...
  </application>
</manifest>

BeaconsPlugin.BackgroundMonitoringCallback is required to react to background monitoring events. The callback will be executed when a monitoring event is detected while the app is running in background. In the snipped above, it will start the Flutter app. It will also allow to receive a callback on the Flutter side. See background monitoring section for more details.

For permission, see below.

Setup specific for iOS

Nothing. Contrary to the general opinion, you do not need to enable any background mode.

For permission, see below.

Permission

In order to use beacons related features, apps are required to ask the location permission. It's a two step process:

  1. Declare the permission the app requires in configuration files
  2. Request the permission to the user when app is running (the plugin can handle this automatically)

For iOS

There are two available permissions in iOS: when in use and always.
The latter is required for background monitoring.

For more details about what you can do with each permission, see:
https://developer.apple.com/documentation/corelocation/choosing_the_authorization_level_for_location_services

Permission must be declared in ios/Runner/Info.plist:

<dict>
  <!-- When in use -->
  <key>NSLocationWhenInUseUsageDescription</key>
  <string>Reason why app needs location</string>

  <!-- Always -->
  <!-- for iOS 11 + -->
  <key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
  <string>Reason why app needs location</string>
  <!-- for iOS 9/10 -->
  <key>NSLocationAlwaysUsageDescription</key>
  <string>Reason why app needs location</string>
  ...
</dict>

For Android

There are two available permissions in Android: coarse and fine.
For beacons related features, there are no difference between the two permission.

Permission must be declared in android/app/src/main/AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
  <!-- or -->
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
</manifest>

How-to

Ranging and monitoring APIs are designed as reactive streams.

  • The first subscription to the stream will start the ranging/monitoring ;
  • The last cancelling (when there are no more subscription) on the stream will stop the ranging/monitoring operation.

Ranging beacons

Beacons.ranging(
  region: new BeaconRegionIBeacon(
    identifier: 'test',
    proximityUUID: '7da11b71-6f6a-4b6d-81c0-8abd031e6113',
  ),
  inBackground: false, // continue the ranging operation in background or not, see below
).listen((result) {
  // result contains a list of beacons
  // list can be empty if no matching beacons were found in range
}

Background ranging

When turned off, ranging will automatically pause when app goes to background and resume when app comes back to foreground. Otherwise it will actively continue in background until the app is terminated by the OS.

Ranging beacons while the app is terminated is not supported by the OS. For this kind of usage, see background monitoring.

Monitoring beacons

Beacons.monitoring(
  region: new BeaconRegionIBeacon(
    identifier: 'test',
    proximityUUID: '7da11b71-6f6a-4b6d-81c0-8abd031e6113',
  ),
  inBackground: false, // continue the monitoring operation in background or not, see below
).listen((result) {
  // result contains the new monitoring state:
  // - enter
  // - exit
}

Background monitoring

When turned off, monitoring will automatically pause when app goes to background and resume when app comes back to foreground. Otherwise it will actively continue in background until the app is terminated by the OS.

Once the app has been terminated, the monitoring will continue.
If a monitoring event happens, the OS will start the app in background for several seconds (nothing will be visible for the user). The OS is providing you the opportunity to perform some quick operation, like showing a local notification.

In order to listen to background monitoring events, you can subscribe to a special stream. This stream is passive: it does not start a monitoring operation. You are still required to start it using Beacons.monitoring(inBackground: true).

Because the OS will run the app in background for several seconds only, before terminating it again, the good place to setup the listener is during app startup.

class MyApp extends StatefulWidget {
  MyApp() {
    Beacons.backgroundMonitoringEvents().listen((event) {
      final BackgroundMonitoringEventType type = event.type // didEnterRegion, didExitRegion or didDetermineState
      final BeaconRegion region = event.region // The monitored region associated to the event
      final MonitoringState state = event.state // useful for type = didDetermineState

      // do something quick here to react to the background monitoring event, like showing a notification
    });
  }

  @override
  _MyAppState createState() => new _MyAppState();
}

For testing background monitoring and what result you should expect, read:
https://developer.radiusnetworks.com/2013/11/13/ibeacon-monitoring-in-the-background-and-foreground.html

Alternatively to starting/stoping monitoring using Beacons.monitoring() stream subscription, you can use the following imperative API:

// Result will be successful if monitoring has started, or contain the reason why it has not (permission denied, etc)
final BeaconsResult result = await Beacons.startMonitoring(
  region: BeaconRegionIBeacon(
    identifier: 'test',
    proximityUUID: 'uuid',
  ),
  inBackground: true,
);

await Beacons.stopMonitoring(
  region: BeaconRegionIBeacon(
    identifier: 'test',
    proximityUUID: 'uuid',
  ),
);

Note that these functions can only start/stop the monitoring.
To receive the associated monitoring events, listen to the stream from Beacons.backgroundMonitoringEvents().

Beacons types

For every API that requires or return a region or a beacon, you can work with the different types of beacons specs.

Regardless of the beacons specs, each region requires an unique identifier that are used by the engine under the hood to uniquely identify and manage a ranging/monitoring request.

Generic

Beacons.ranging(region: BeaconRegion(
    identifier: 'test',
    ids: ['id1', 'id2', 'id3'],
  ),
).listen((result) {
  final Beacon beacon = result.beacons.first;
});

iBeacon

Beacons.ranging(region: BeaconRegionIBeacon(
    identifier: 'test',
    proximityUUID: 'some-uuid',
    major:0,
    minor: 0,
  ),
).listen((result) {
  final BeaconIBeacon beacon = BeaconIBeacon.from(result.beacons.first);
});

Under the hood

  • iOS uses native iOS CoreLocation
  • Android uses the third-party library android-beacon-library (Apache License 2.0)

Each technology has its own specificities.
The plugin does its best to abstract it and expose a common logic, but for an advanced usage, you would probably still need to familiarize yourself with the native technology.

Beacons plugin development is sponsored by Pointz.

Author

Beacons plugin is developed by Loup, a mobile development studio based in Montreal and Paris.
You can contact us at hello@intheloup.io

License

Apache License 2.0

[0.3.0]

  • Fix: Background monitoring on Android
  • New: Settings API
  • New: Imperative start/stop monitoring API
  • Breaking change: Additional plugin configuration required for Android

[0.2.1]

  • Breaking change: Renamed BeaconRegionIBeacon.wrap() to from()

[0.2.0]

  • Breaking change: Renamed backgroundMonitoringEvent.name to type (enum)

[0.1.2]

  • New: Exposed BackgroundMonitoringEvents
  • Breaking change: Renamed MonitoringEvent to MonitoringState

[0.1.1]

  • Fix: iOS background support

[0.1.0]

  • New feature: Android support
  • Revamp public API to match new Android support
  • Revamp example

[0.0.2]

  • Revamp public API
  • New feature: iBeacons monitoring (iOS only)

[0.0.1] - Initial release

  • New feature: iBeacons ranging (iOS only)

example/lib/main.dart

//  Copyright (c) 2018 Loup Inc.
//  Licensed under Apache License v2.0

import 'package:beacons/beacons.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_local_notifications/initialization_settings.dart';
import 'package:flutter_local_notifications/notification_details.dart';
import 'package:flutter_local_notifications/platform_specifics/android/initialization_settings_android.dart';
import 'package:flutter_local_notifications/platform_specifics/android/notification_details_android.dart';
import 'package:flutter_local_notifications/platform_specifics/ios/initialization_settings_ios.dart';
import 'package:flutter_local_notifications/platform_specifics/ios/notification_details_ios.dart';

import 'tab_monitoring.dart';
import 'tab_ranging.dart';

void main() => runApp(new MyApp());

class MyApp extends StatefulWidget {
  MyApp() {
    Beacons.loggingEnabled = true;

    int notifId = 0;

    Beacons.backgroundMonitoringEvents().listen((event) {
      FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
          new FlutterLocalNotificationsPlugin();
      InitializationSettingsAndroid initializationSettingsAndroid =
          new InitializationSettingsAndroid('app_icon');
      InitializationSettingsIOS initializationSettingsIOS =
          new InitializationSettingsIOS();
      InitializationSettings initializationSettings =
          new InitializationSettings(
              initializationSettingsAndroid, initializationSettingsIOS);
      flutterLocalNotificationsPlugin.initialize(initializationSettings);

      NotificationDetailsAndroid androidPlatformChannelSpecifics =
          new NotificationDetailsAndroid('your channel id', 'your channel name',
              'your channel description');
      NotificationDetailsIOS iOSPlatformChannelSpecifics =
          new NotificationDetailsIOS();
      NotificationDetails platformChannelSpecifics = new NotificationDetails(
          androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
      flutterLocalNotificationsPlugin.show(
        ++notifId,
        event.type.toString(),
        event.state.toString(),
        platformChannelSpecifics,
      );
    });

    Beacons.configure(BeaconsSettings(
      android: BeaconsSettingsAndroid(
        logs: BeaconsSettingsAndroidLogs.info,
      ),
    ));
  }

  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new CupertinoTabScaffold(
        tabBar: new CupertinoTabBar(
          items: <BottomNavigationBarItem>[
            new BottomNavigationBarItem(
              title: new Text('Track'),
              icon: new Icon(Icons.location_searching),
            ),
            new BottomNavigationBarItem(
              title: new Text('Monitoring'),
              icon: new Icon(Icons.settings_remote),
            ),
            new BottomNavigationBarItem(
              title: new Text('Settings'),
              icon: new Icon(Icons.settings_input_antenna),
            ),
          ],
        ),
        tabBuilder: (BuildContext context, int index) {
          return new CupertinoTabView(
            builder: (BuildContext context) {
              switch (index) {
                case 0:
                  return new RangingTab();
                case 1:
                  return new MonitoringTab();
                default:
                  return new Container(
                    child: new Center(
                      child: new Text('TBD'),
                    ),
                  );
              }
            },
          );
        },
      ),
    );
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  beacons: ^0.3.0

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter packages get

Alternatively, your editor might support flutter packages get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:beacons/beacons.dart';
  
Version Uploaded Documentation Archive
0.3.0 Jun 1, 2018 Go to the documentation of beacons 0.3.0 Download beacons 0.3.0 archive
0.2.1 May 30, 2018 Go to the documentation of beacons 0.2.1 Download beacons 0.2.1 archive
0.2.0 May 30, 2018 Go to the documentation of beacons 0.2.0 Download beacons 0.2.0 archive
0.1.2 May 30, 2018 Go to the documentation of beacons 0.1.2 Download beacons 0.1.2 archive
0.1.1 May 29, 2018 Go to the documentation of beacons 0.1.1 Download beacons 0.1.1 archive
0.1.0 May 28, 2018 Go to the documentation of beacons 0.1.0 Download beacons 0.1.0 archive
0.0.2 May 23, 2018 Go to the documentation of beacons 0.0.2 Download beacons 0.0.2 archive
0.0.1 May 18, 2018 Go to the documentation of beacons 0.0.1 Download beacons 0.0.1 archive
Popularity:
Describes how popular the package is relative to other packages. [more]
75
Health:
Code health derived from static analysis. [more]
90
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
80
Overall:
Weighted score of the above. [more]
81
Learn more about scoring.

We analyzed this package on Dec 5, 2018, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.1.0
  • pana: 0.12.7
  • Flutter: 1.0.0

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Health issues and suggestions

Document public APIs (-9.72 points)

104 out of 107 API elements (library, class, field or method) have no adequate dartdoc content. Good documentation improves code readability and discoverability through search.

Maintenance suggestions

The description is too short. (-20 points)

Add more detail about the package, what it does and what is its target use case. Try to write at least 60 characters.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=1.19.0 <3.0.0
flutter 0.0.0
streams_channel ^0.2.1 0.2.2
Transitive dependencies
collection 1.14.11
meta 1.1.6
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8