Pluggable's Fanmeter Plugin for Flutter apps

The Fanmeter plugin is the one responsible for enabling Fanmeter in any mobile application. It is a simple plug-&-play plugin that makes available a set of methods that can be used to allow users to participate in activations such as the FAN OF THE MATCH or the SUPER FAN.

Fully-automatized vs Manual Fanmeter

There are two possible types of integration. One is fully-automatized and uses a default native view that is launched to your users for them to participate in Fanmeter - it also launches and delivers push notifications as soon as the event starts and finishes. If, on the other hand, you wish to create your own Fanmeter view, you will follow a manual approach.

  1. Fully-automatized Fanmeter: you want everything automated (including a default Fanmeter view). You should also integrate with FCM to handle received notifications that start the event (in summary, you'll need to use the execute, launchFanmeterNotification and, optionally, the launchFanmeterView methods);

  2. Manual Fanmeter: you want to handle the conditions yourself and develop your own view (just start calling the startService, stopService, and isServiceRunning methods).

Pre-Conditions

Meta-Data

For Android, push permission is required so that a notification is shown to the user so that he knows that a foreground service is running. Also, note that the Location permission is needed for the fans to participate in the geo-restricted events. Hence, you need to ask for such permissions.

For iOS, add the Background Modes capability and enable Location Updates. Also, you must open your Info.plist file and add the following code at the bottom of the file:

<key>UIBackgroundModes</key>
<array>
    <string>fetch</string>
    <string>location</string>
    <string>remote-notification</string>
</array>
<key>NSLocationTemporaryUsageDescriptionDictionary</key>
<dict>
    <key>PreciseLocationRequired</key>
    <string>Access to precise location is required during geo-restriced events!</string>
</dict>
<key>NSLocationAlwaysUsageDescription</key>
<string>Location access is required to participate in geo-restricted events!</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Location access is required to participate in geo-restricted events!</string>

Note that, for Android only, Fanmeter is required to use a Data Sync foreground service to communicate non-intrusive sensor data with Pluggable's server. Since API 34 of Android, when publishing an app that uses such services, you are required to fill a Policy Declaration where you must justify the need for such services. In Fanmeter's case, when filling such policy, you will be asked the question "What tasks require your app to use the FOREGROUND_SERVICE_DATA_SYNC permission?".

There, you should:

  1. Select the option OTHER in Other tasks;

  2. Provide the following video link:

    https://youtu.be/w4d7Pgksok0
    
  3. Provide the following description:

    Fanmeter is an Android SDK, incorporated in this app, that uses a Data Sync foreground service to communicate non-intrusive sensor data with Pluggable's servers, which are used to quantify the engagement of the user in real-time. The foreground service must start as soon as the user opts to participate in the event (so that it can collect and communicate data) and must keep running until the user himself decides to terminate his/her participation.
    

Push Notifications

Before using this plugin, if you want a fully-automated experience, you should guarantee that your app already integrates with Firebase Cloud Messaging so that your app can receive push notifications.

  1. First install FlutterFire, a tool which automatically configures your app to use firebase;

  2. Then, install firebase_messaging, a cross-platform messaging solution;

  3. Then, to start using the Cloud Messaging package within your project follow these steps;

  4. Integrating the Cloud Messaging plugin on iOS requires additional setup before your devices receive messages. The full steps are available here, but the following prerequisites are required to be able to enable messaging:

    • You must have an active Apple Developer Account;
    • You must have a physical iOS device to receive messages.
  5. Also for iOS:

    • If you are using swift, in your AppDelegate.swift make sure you have added the first code;
    • If you're using flutter with objective-c, add the second code to your appdelegate.m file.
    import Firebase
    
    FirebaseApp.configure() //add this before the code below
    GeneratedPluginRegistrant.register(with: self)
    
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
        [FIRApp configure]; //add this at the top
        // ...
    }
    

NOTE: FCM via APNs does not work on iOS Simulators. To receive messages & notifications a real device is required. The same is recommended for Android.

Set up the Fanmeter Plugin in your Flutter App

Install the Plugin

After configuring your app to integrate with FCM, you are ready to use this plugin to properly engage with your fans! To install the plugin just run, in the root of the project:

flutter pub add fanmeter

Or run flutter pub upgrade to update to the latest compatible versions of all the dependencies listed in the pubspec.yaml file.

Note that for Android, to customize the used notification icon just add the desired icon in the Android's drawable folder and name it ic_push_app_icon. Otherwise, a default icon, not related to your app, will be used.

Method initialize and getEventData

The initialize method is mandatory for both fully-automatized and manual scenarios. It is responsible for initializing the SDK and must be invoked before using any other method (a possible approach is to invoke it in the main app process).

import 'package:fanmeter/fanmeter.dart';

// ...

String COMPANY_NAME = 'your_company_name';
String COMPANY_KEY = 'your_company_key';
String EXTERNAL_USER_ID = 'your_user_id';
String EXTERNAL_TOKEN_ID = 'the_id_of_the_device';
String? EXTERNAL_USER_EMAIL = 'email@domain.com';
String? FCM_TOKEN = 'the_fcm_token';
String? TICKET_NUMBER = 't-1234';
String? TICKET_STAND;
String? REGULATION_URL;
String? NOTIFICATION_CLASS_RESPONSE;
bool? FANMETER_LOG = true;

final _fanmeterPlugin = Fanmeter();

// When the Fanmeter SDK is initialized, it initializes all company and user data.
final result = await _fanmeterPlugin.initialize(
    companyName: COMPANY_NAME,
    companyKey: COMPANY_KEY,
    externalUserId: EXTERNAL_USER_ID,
    externalTokenId: EXTERNAL_TOKEN_ID,
    externalUserEmail: EXTERNAL_USER_EMAIL,
    fcmToken: FCM_TOKEN,
    ticketNumber: TICKET_NUMBER,
    ticketStand: TICKET_STAND,
    urlRegulation: REGULATION_URL,
    log: FANMETER_LOG
);

Where:

  • COMPANY_NAME, is the name of your company in Fanmeter;
  • COMPANY_KEY, your company's license key;
  • EXTERNAL_USER_ID, the user identifier in your db (can be the username, the uuid, ...);
  • EXTERNAL_TOKEN_ID, the individual smartphone identifier (allows for the same account in different devices);
  • EXTERNAL_USER_EMAIL, the user's email. Nullable;
  • FCM_TOKEN, the FCM token id of the user. Nullable;
  • TICKET_NUMBER, the user's ticket number - used for additional analytics. Nullable;
  • TICKET_STAND, the stand where the user is - used for additional analytics. Nullable;
  • REGULATION_URL, the URL to the regulation for your events. Nullable;
  • FANMETER_LOG, enables additional logging.

An additional method exists, called getEventData, being used to obtain the full data of a particular Fanmeter event, in a dictionary, including the defined rewards and leaderboard classifications, if existing. If null, or not provided, this returns the closest event to date:

// You should manage the events to get their name programmatically instead of an hardcoded string.
// If null, will return the closest event to date.
String? EVENT_NAME = "Round 1 2024-2025";

// After initialized, you will be able to use the SDK methods.
final result = await _fanmeterPlugin.getEventData();

// OR.

final result = await _fanmeterPlugin.getEventData(EVENT_NAME);

Fully-automated Fanmeter

After initializing the Plugin, you are now ready to start calling Fanmeter. In particular, if you want to automate the entire process, this library exposes three methods, that must be called as demonstrated below. In particular:

  • execute, launches the SDK Fanmeter default's view as soon as a notification is clicked by the user;
  • launchFanmeterNotification, launches a local notification to the user, which is required by Android when the app is in the foreground;
  • launchFanmeterView, launches the SDK Fanmeter default's view. It can be associated with a button or banner in your app, redirecting the user to the Fanmeter native view, allowing users without notification permissions to participate in the event. It will open the Fanmeter view with the event with the closest date to the current date.

The execute method is used for backgrounded processes and will open the default Fanmeter view to the user. On the other hand, the launchFanmeterNotification method launches a local notification when the Android app is in a foreground state. An example is as follows, used in your .dart files as demonstrated in the next lines.

import 'package:fanmeter/fanmeter.dart';

// ...

/// Receive pushes while in the foreground.
void _firebaseMessagingForegroundHandler(RemoteMessage message) async {
    if(message.notification != null) {
        Map<String, String> notificationData = message.data.map((key, value) => MapEntry(key, value.toString()));
        final result = await _fanmeterPlugin.launchFanmeterNotification(
            notificationData,
            NOTIFICATION_CLASS_RESPONSE
        );
    }
}

/// Handle push tap by the user.
void _handlePushTap(RemoteMessage message) async {
    Map<String, String> notificationData = message.data.map((key, value) => MapEntry(key, value.toString()));
    final result = await _fanmeterPlugin.execute(
        notificationData, 
        NOTIFICATION_CLASS_RESPONSE
    );
}

Future<void> setupInteractedMessage() async {
    // Get any messages which caused the application to open from a terminated state.
    RemoteMessage? initialMessage = await FirebaseMessaging.instance.getInitialMessage();
    if(initialMessage != null) {
        _handlePushTap(initialMessage);
    }
    // Also handle any interaction when the app is in the background.
    FirebaseMessaging.onMessageOpenedApp.listen(_handlePushTap);
}

@override
void initState() {
    // ...

    // Listen for foreground pushes.
    FirebaseMessaging.onMessage.listen(_firebaseMessagingForegroundHandler);

    // Handle notification tap.
    setupInteractedMessage();

    // ...
}

Where:

  • notificationData, is the remote data received with the notification;
  • NOTIFICATION_CLASS_RESPONSE, the name of the class that is being instantiated when the user clicks the notification - example: "com.company.activities.SearchActivity" (null opens the app's default view).

Finally, the launchFanmeterView method should be called on a button click, redirecting users to Fanmeter's default view. It can, p.e., be associated with a button/banner in your app, redirecting the user to the Fanmeter native view, allowing users without notification permissions to participate in the event. This method accepts an eventId, that should be obtained using the getEventData method. If a null eventId is passed, this method will open the closest available event to the current date.

final result = await _fanmeterPlugin.launchFanmeterView(eventId);

// OR.

// Returns the closest available event to the current date.
final result = await _fanmeterPlugin.launchFanmeterView();

These functions return the following values:

  • 1, success;
  • -80, no GPS/PUSH permissions;
  • -81, GPS disabled;
  • -82, invalid event coordinates;
  • -89, SDK not initialized;
  • -91, invalid notification data;
  • -92, invalid company license;
  • -93, invalid event;
  • -94, event not happening now;;
  • -95, invalid external user data;
  • -96, failed to get event data;
  • -97, failed to start the Fanmeter service;

You are also required to subscribe the user to a FCM topic so that he/she can receive event notifications. This can be done, for example, as follows:

Future<void> setupToken() async {
    // Get the token each time the application loads.
    FCM_TOKEN = await FirebaseMessaging.instance.getToken();
    // Subscribe to a specific topic.
    await FirebaseMessaging.instance.subscribeToTopic('football_senior');
}

Manual Fanmeter

If you want full control and implement your own UI, this library exposes three methods, that must be called as demonstrated below. In particular:

  • startService, starts the Fanmeter service that enables Fanmeter for your client's device during a particular event;
  • stopService, stops the Fanmeter service. The service will, still, terminate automatically as soon as the event ends. This returns 1, if success, otherwise an error code;
  • isServiceRunning, used to check the current status of the Fanmeter service. Returns 1, if the service is running, otherwise 0.

The startService method is used to start the Fanmeter service. This method accepts an eventId, that should be obtained using the getEventData method and should be called as follows (associated, for example, to a particular button):

// You can obtain the eventId of an event by calling the getEventData method.
final result = await _fanmeterPlugin.startService(
    eventId, 
    NOTIFICATION_CLASS_RESPONSE
);

Where:

  • eventId, the id of the event the user will participate when the start service is called;
  • NOTIFICATION_CLASS_RESPONSE, the name of the class that is being instantiated when the user clicks the notification - example: "com.company.activities.SearchActivity" (null opens the app's default view).

This method returns the following values:

  • 1, success;
  • -80, no GPS/PUSH permissions;
  • -81, GPS disabled;
  • -82, invalid event coordinates;
  • -89, SDK not initialized;
  • -92, invalid company license;
  • -93, invalid event;
  • -94, event not happening now;;
  • -95, invalid external user data;
  • -96, failed to get event data;
  • -97, failed to start the Fanmeter service;

The stopService method is used to stop the Fanmeter service (can be toggled with the previous method). Even if the user does not explicitly stop the service, it will automatically stop as soon as the event finishes. This returns 1, if success, otherwise an error code.

final result = await _fanmeterPlugin.stopService();

Finally, the isServiceRunning method is used to check the current status of the Fanmeter service. This returns true, if the service is running, otherwise false.

final result = await _fanmeterPlugin.isServiceRunning();

Additional info

Other important methods are to request user permission to be able to send notifications and request GPS permission. Also, get the user token and listen for changes to get the user FCM_TOKEN and update it when it changes.

Future requestPermission() async {
    FirebaseMessaging messaging = FirebaseMessaging.instance;
    // Ask for push permissions.
    NotificationSettings settings = await messaging.requestPermission(
        alert: true,
        announcement: false,
        badge: true,
        carPlay: false,
        criticalAlert: false,
        provisional: true,
        sound: true,
    );
    print('User granted permission: ${settings.authorizationStatus}');
    // Presentation for foreground push.
    await messaging.setForegroundNotificationPresentationOptions(
        alert: true,
        badge: true,
        sound: true,
    );	
}

Future<void> updateFcmToken() async {
    // Get the token each time the application loads.
    FCM_TOKEN = await FirebaseMessaging.instance.getToken();
}

For full compatibility, attention to the used versions of XCODE, SWIFT and COCOAPODS. Recommended versions are XCODE=15, SWIFT=5.9, and COCOAPODS=1.14.2. For more info visit https://pluggableai.xyz/ or give us feedback to info@pluggableai.xyz.