@fivvy/ionic-contextual-profiler
v3.2.6
Published
Contextual profiler library for ionic
Readme
Getting started @fivvy/ionic-contextual-profiler
Contextual Profiler SDK offers a comprehensive and efficient solution for collecting valuable information about your users. With this powerful tool, you will be able to gather relevant data that will allow you to conduct in-depth analysis and gain a clear understanding of your users' behavior, preferences, and needs.
⚠️ Important Notice: This library does not support iOS devices.
Please be aware that this library is currently only available for Android. It will not work on iOS devices. Ensure that your project is intended for Android platforms before integrating this library.
Recommendations
- IONIC VERSION: Actually tested on Ionic 7
- CAPACITOR VERSION: 3.9 or higher
- ANDROID API LEVEL: 21 a 34
- MIN JAVA VERSION: jdk11 (we recommend jdk17)
Installation
Please read this entire section.
npm
npm install @fivvy/ionic-contextual-profiler yarn
yarn add @fivvy/ionic-contextual-profiler Remember to update the new Android Plugin with capacitor
npx cap syncthe terminal will log the name of the plugin
Example
√ Updating Android plugins in 9.74ms
[info] Found 5 Capacitor plugins for android:
@capacitor/[email protected]
@capacitor/[email protected]
@capacitor/[email protected]
@capacitor/[email protected]
@fivvy/ionic-contextual-profilerAndroid
Proguard
If you have any obfucastion tool in your project, you'll need to exclude this package to work as intended in release builds.
Create a new file called proguard-rules.pro in /android/app with this content:
-keep class com.fivvy.profiler.** { *; }
-keep class * extends com.fivvy.profiler.** { *; }
-keepclassmembers class com.fivvy.profiler.** {
*;
}
-keepattributes *Annotation*Add the following settings in build.gradle within /android/app
buildTypes {
release {
...
minifyEnabled true
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}Permissions
AndroidManifest
Necessary to add this xmlns:tools inside the tag manifest in the AndroidManifest inside android/app/src/main folder.
<manifest xmlns:tools="http://schemas.android.com/tools">Need to add these permissions in the AndroidManifest inside android/app/src/main folder.
<uses-permission android:name="android.permission.INTERNET" />Proyect Level build.gradle
Add the Maven repository URL to your project-level build.gradle file:
allprojects {
repositories {
google()
mavenCentral()
maven {
url "https://gitlab.com/api/v4/projects/58175283/packages/maven"
}
}
}App build.gradle
Add the implementation dependency to your app-level build.gradle file:
dependencies {
(...)
implementation 'com.fivvy:fivvy-lib:3.2.6@aar'
}make sure you also have:
implementation 'androidx.appcompat:appcompat:1.4.0'
implementation 'androidx.work:work-runtime:2.8.0'
implementation 'com.google.code.gson:gson:2.8.9'
implementation 'com.squareup.okhttp3:okhttp:4.9.2'
implementation 'androidx.security:security-crypto-ktx:1.1.0-alpha04'
implementation 'com.scottyab:rootbeer-lib:0.1.1'Send data to Fivvy's analytics service
Example of use
import { ContextualProfiler } from '@fivvy/ionic-contextual-profiler ';
const { initContextualDataCollection } = ContextualProfiler;
const sendData = async () => {
const res = await initContextualDataCollection({
customerId: "ionic-user-2", // Represents an identifier of the current user
apiKey: ENV.API_KEY, // ApiKey of Fivvy's API - ENVIRONMENT VARIABLE
apiSecret: ENV.API_SECRET, // ApiSecret of Fivvy's API - ENVIRONMENT VARIABLE
appUsageDays: 30, // Integer that represents the last days to recollect the app usage information of the user. Recommended default value: 30
authApiUrl: ENV.AUTH_API_URL, // URL of the Fivvy's Auth API: https://api.fivvyforbusiness.com/b2b-auth/auth/v1/users/login
sendDataApiUrl: ENV.SEND_DATA_API_URL // URL of the Fivvy's Analytics Data API: https://api.fivvyforbusiness.com/b2b-intake/intake/v2/context
});
console.log("response: ", res); // RESPONSE IS CONTEXTUAL DATA OBJECT
};Module Functions
All the information about the package and how to use functions.
| Methods | Params value | Return value | Description |
|--- |--- |--- |--- |
| initContextualDataCollection | InitConfig {customerId: String, apiKey: String, apiSecret: String, appUsageDays: Int, authApiUrl: String, sendDataApiUrl: String} | ContextualData | Initiates data collection, sending it to the Fivvy's Analytics Data API.
| getDeviceInformation | Empty | Promise<IHardwareAttributes> | Returns the device hardware information of the customer. |
| getAppsInstalled | Empty | Promise<IInstalledApps[]> | Returns an IInstalledApps Array for all the queries in AndroidManifest that user had install in his phone. |
Interfaces
Here you can find the interfaces that sdk uses
`initContextualCollectionData param object interface`
InitConfig {
customerId: string,
apiUsername: string,
apiPassword: string,
appUsageDays: number,
authApiUrl: string,
sendDataApiUrl: string
}
`getDeviceInformation return interface`
IHardwareAttributes {
api_level: string;
device_id: string;
device: string;
hardware: string;
brand: string;
manufacturer: string;
model: string;
product: string;
tags: string;
type: string;
base: string;
id: string;
host: string;
fingerprint: string;
incremental_version: string;
release_version: string;
base_os: string;
display: string;
battery_status: number;
publicIP: string
}
`getAppsInstalled return object interface`
IInstalledApps {
appName?: string;
packageName: string;
category?: string;
installTime?: string;
lastUpdateTime?: string;
versionCode?: string;
versionName?: string;
}Example
Getting the installed apps
Recovery of applications installed on the user's device.
getAppsInstalled().then(data => console.log('Installed apps:', data));
// expected output
Installed Apps: [{"appName": "WhatsApp", "category": "Social", "installTime": "2023.02.15 20:07:35", "lastUpdateTime": "2023.08.16 14:52:12", "packageName": "com.whatsapp", "versionCode": "231676002", "versionName": "2.23.16.76"}]
Debug mode
Debug Mode Configuration
To enable and properly use the debug mode, follow these steps:
Requirements for Debug Mode
The project must have the
BuildConfigclass generated, which is standard in Ionic projects configured for Android. If your project does not generateBuildConfig, proceed to step 2.If
BuildConfigis not automatically generated or does not include the required property:- Open the
build.gradlefile located at/android/app. - Add the following configurations:
android { ... buildFeatures { buildConfig true } }
- Open the
⚠️ Important: The applicationId and namespace in your project must be identical. Debug mode will not work properly if these values are different.
General Information
⚠️ Important Notice: iOS Compatibility
This library is not compatible with iOS devices. It is specifically designed for Android platforms, and no support for iOS is provided. Please refrain from using this library in iOS-based projects, as it will not function as intended.
Appendix: advanced features (optional)
Permissions
On android you must request permissions beforehand. This part is divided into two sections to show how to open the usage settings on Android using a custom modal dialog or directly without a modal.
AndroidManifest
Need to add these permissions in the AndroidManifest inside android/app/src/main folder.
<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" tools:ignore="ProtectedPermissions" />Using the Plugin to Open Usage Settings with Custom Dialog
To open the usage settings with a custom dialog and an image from the assets folder, follow these steps:
Step 1: Create a Method to Convert Image to Byte Array
Create a method to read an image from the assets folder and convert it to a byte array.
async function convertImageToByteArray(imagePath: string): Promise<number[]> {
const response = await fetch(imagePath);
const blob = await response.blob();
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => {
const arrayBuffer = reader.result as ArrayBuffer;
const byteArray = new Uint8Array(arrayBuffer);
resolve(Array.from(byteArray));
};
reader.onerror = reject;
reader.readAsArrayBuffer(blob);
});
}
Step 2: Use the Plugin with Custom Parameters
Include the method in your Ionic component and use it to open the usage settings WITH a custom dialog.
import { Plugins } from '@capacitor/core';
const { ContextualProfiler } = Plugins;
async function showUsageSettingsDialog() {
try {
// Make sure the path to your image is correct. Note If the image does not open, check that the image is in the build/dist folder to be accessible
const imagePath = await convertImageToByteArray('assets/example.png');
// ln could be ES, EN, PR at the moment
await ContextualProfiler.createOpenUsageSettingsUseCase({
ln: 'ES',
appName: 'AppDemo',
appDescription: 'Some Description',
modalText: 'Some guide text',
imagePath: imagePath || [0,0,0],
imageView: 1,// integer value, 0: no image; 1: default image, 2: app logo
buttonRadius: 25.0,// float value, set button border radius
modalRadius: 25.0,// float value, set modal border radius
color: '#50C7FA',// hex color value, set color of dialog title, accept background color and cancel button text color
dialogTitle: 'Custom Usage Information Title',
dialogMessage1: 'Custom message 1 about usage permissions.',
dialogMessage2: 'Custom message 2 about privacy and data collection.',
blacklist: null // (Optional) List of device manufacturers for which the usage settings should be avoided. On some devices, especially from certain manufacturers as Xiaomi, a system warning might be displayed when attempting to access the usage settings. To prevent this action on those devices, you can:
//- Pass `null`: This will apply a default list of manufacturers known to have this issue.
// - Provide a custom list of manufacturers as an array (`["manufacturer1", "manufacturer2"]`): This will prevent the settings from being accessed only on devices from those specific brands.
//- Pass an empty array `[]`: This will allow the settings to be accessed on all devices without any restrictions.
});
} catch (e) {
console.error('Error opening usage settings', e);
}
}Opening Usage Settings Directly
If you prefer to open the usage settings directly without a custom dialog, follow these steps:
Use the Plugin Directly
Include the method in your Ionic component and use it to open the usage settings directly.
import { Plugins } from '@capacitor/core';
const { ContextualProfiler } = Plugins;
async function showUsageSettings() {
try {
await ContextualProfiler.createOpenUsageSettingsDirectlyUseCase({blacklist: ['samsung']});// - blacklist (Optional) List of device manufacturers for which the usage settings should be avoided. On some devices, especially from certain manufacturers as Xiaomi, a system warning might be displayed when attempting to access the usage settings. To prevent this action on those devices, you can:
//- Pass `null`: This will apply a default list of manufacturers known to have this issue.
// - Provide a custom list of manufacturers as an array (`["manufacturer1", "manufacturer2"]`): This will prevent the settings from being accessed only on devices from those specific brands.
//- Pass an empty array `[]`: This will allow the settings to be accessed on all devices without any restrictions.
} catch (e) {
console.error('Error opening usage settings', e);
}
}blacklist Parameter
The blacklist parameter is an array of strings containing the names of device manufacturers for which you want to disable a certain function. If the device is from a manufacturer listed in this array, the function will not perform any action.
blacklist Behavior:
- Array with specific manufacturers: If the array contains manufacturer names, the function will be disabled on devices from those brands. Example:
blacklist: ["xiaomi", "huawei"]- Empty Array: The feature will work on any manufacturer device. Example:
blacklist: []- Null value: The feature will use a default blacklist, here are the default blacklisted manufacturers: ["xiaomi", "huawei", "oppo", "vivo", "realme", "lenovo", "meizu", "oneplus", "zte", "nubia"]
blacklist: nullDevice manufacturer
This fucntion will return the current device manufacturer, this could be useful if you need to implement more complex logic in your app regarding the device manufacturer.
const result = await ContextualProfiler.logDeviceManufacturer();
console.log("Device Manufacturer:", result.message);Here's a full list of manufacturers names in Android: Android manufacturer names
By following these steps, you can either use a custom dialog to guide the user or open the usage settings directly without additional prompts.
Module Functions
All the information about the package and how to use functions.
| Methods | Params value | Return value | Description |
|--- |--- |--- |--- |
| getAppUsage | Int days. Represent the last days to get the usage of each app. | Promise<IAppUsage[]> | Returns an IAppUsage Array for all the queries in AndroidManifest that user had install in his phone or null if user doesn’t bring usage access. | Returns null if the user doesnt brings access to the App Usage or an IAppUsage Array for the all used aplications. |
| openUsageAccessSettings | {ln: String, appName: String, appDescription: String, modalText: String, imagePath: byte[], imageView: number, buttonRadius: Float, modalRadius: Float, color: String, dialogTitle: String, dialogMessage1: String, dialogMessage2: String} | Boolean | Open settings with pre-built modal view to grant app usage permission. |
| openUsageAccessSettingsDirectly | Empty | Boolean | Open settings view without pre-built modal to grant app usage permission. |
Interfaces
Here you can find the interfaces that sdk uses
`getAppUsage return object interface`
IAppUsage {
appName: string;
usage: number;
packageName: string;
}Changelog
[3.2.6] - 15-05-2025
Changed
- update manifest default
Terms of use
All content here is the property of Fivvy, it should not be used without their permission.
