2.0.2 • Published 11 months ago

@fivvy/cordova-plugin-contextual-profiler v2.0.2

Weekly downloads
-
License
ISC
Repository
-
Last release
11 months ago

Getting started @fivvy/cordova-plugin-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.

See the full API for more methods.

Recommendations

  • CORDOVA ^12.0.1
  • ANDROID API LEVEL: 21 to 34
  • MIN JAVA VERSION: jdk8
  • GRADLE DISTRIBUTION: gradle-7.5

Installation

Please read this entire section.

cordova plugin add @fivvy/cordova-plugin-contextual-profiler

Android

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'
        }
    }

Proyect Level build.gradle

make sure you have the Maven repository URL on your project-level build.gradle file:

allprojects {
    repositories {
        google()
        mavenCentral()
         maven {
            url "https://gitlab.com/api/v4/projects/58175283/packages/maven"
    }
        
    }
}

App build.gradle

and the implementation dependency on your app-level build.gradle file:

dependencies {
    (...)
    implementation 'com.fivvy:fivvy-lib:2.1.0@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'

AndroidManifest

Necesary to add this xmlns:tools insde the tag manifest on AndroidManifest.xml insde android/app/src/main folder.

<manifest 
  <!-- Others manifest properties -->
  xmlns:tools="http://schemas.android.com/tools"
>

Need to add these permissions in the AndroidManifes.xml file inside android/app/src/main before aplication tag.

<manifest>
  <!-- others aplications tags -->
  <uses-permission  android:name="android.permission.INTERNET" />
  <uses-permission  android:name="android.permission.PACKAGE_USAGE_STATS"  tools:ignore="ProtectedPermissions" />

  <!-- List of apps that you want to check on customer device -->
  <queries>
    <!-- List of package's [Max 100] -->
    <package android:name="com.whatsapp"/> <!-- WhatsApp Messenger -->
    <package android:name="com.facebook.katana"/> <!-- Facebook -->
    <package android:name="com.mercadopago.android"/> <!-- Mercado Pago -->
    
  </queries>

  <application>
    <!-- ... -->
  </application>
</manifest>

Integration in App

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.

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) {
    try {
      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;
          const byteArray = new Uint8Array(arrayBuffer);
          resolve(Array.from(byteArray));
        };
        reader.onerror = reject;
        reader.readAsArrayBuffer(blob);
      });
    } catch (error) {
      console.error("Error converting image to byte array: ", error);
    }
  }

Get user permission to check the app's usage

  async function testOpenUsageSettings() {
    const lang = "ES";    // lang could be ES, EN, PR at the moment
    const appName = "appname"; // string value with your app name
    const appDescription = "app description"; // optional description text. Recommended length: 3 or 4 words
    const imagePath = await convertImageToByteArray('/img/logo.png'); // Make sure the path to your image is correct.
    const modalText = "modal text"; // optional modal text. Recommended length: 3 or 4 words
    const title = "titulo"; // Title of the dialog displayed to the user before redirecting to the settings screen for permissions.
    const message1 = "mensaje 1";  // Custom Message of the dialog displayed to the user before redirecting to the settings screen for permissions.
    const message2 = "mensaje 2";// Other custom Message of the dialog displayed to the user before redirecting to the settings screen for permissions.
    const blacklist = null // - 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.

    if (imagePath && imagePath.length > 0) {
        cordova.plugins.ContextualProfilerPlugin.openUsageSettings(lang, appName, appDescription, imagePath, modalText, title, message1, message2, blacklist, function(result) {
            console.log('Success: ' + result);
            document.getElementById('openUsageSettingsResult').innerText = 'Success: ' + result;
        }, function(error) {
            console.log('Error: ' + error);
            document.getElementById('openUsageSettingsResult').innerText = 'Error: ' + error;
        });
    } else {
        document.getElementById('openUsageSettingsResult').innerText = 'Image path array is empty or not valid.';
    }
}

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 component and use it to open the usage settings directly.

function testOpenUsageSettingsDirectly() {
   cordova.plugins.ContextualProfilerPlugin.openUsageSettingsDirectly(blacklist, function(result) {
       console.log('Success: ' + result);
       document.getElementById('openUsageSettingsDirectlyResult').innerText = 'Success: ' + result;
   }, function(error) {
       console.log('Error: ' + error);
       document.getElementById('openUsageSettingsDirectlyResult').innerText = 'Error: ' + error;
   });
}

Send data to Fivvy's analytics service

This function will allow your app to send the information of each user to the Fivvy Analytic's API. You must add on some view or loading component that can send the data at least 1 time a day.

document.addEventListener('deviceready', onDeviceReady, false);

function onDeviceReady() {
    console.log('Running cordova-' + cordova.platformId + '@' + cordova.version);
    document.getElementById('deviceready').classList.add('ready');
}
const customerId = 'customer-id-01';
const days = 30;
const forceInit = false; // Boolean parameter that controls the data submission and collection process. If set to `false`, data will not be re-sent or collected until 24 hours have passed since the last submission. If set to `true`, this condition will be ignored, and data will be sent or collected immediately, regardless of the time elapsed.
const COMPANY_NAME = 'FIVVY-TEST';
const API_KEY = 'XXXXXXX';
const API_SECRET = 'XXXXXXX';
const AUTH_API_URL = 'https://XXXXXXXXXXX';
const SEND_DATA_API_URL = 'https://XXXXXXXXXXX';

function testSendData() {
    cordova.plugins.ContextualProfilerPlugin.initContextualDataCollection(customerId, API_KEY, API_SECRET, AUTH_API_URL,SEND_DATA_API_URL,days, forceInit, function(result) {
        console.log('Success: ' + result);
    }, function(error) {
        console.log('Error: ' + error);
    });
}
document.getElementById('sendData').addEventListener('click', testSendData);

API

All the information about the package and how to use functions.

MethodsParams valueReturn valueDescription
initContextualDataCollection(customerId: String, apiKey: String, apiSecret: String, appUsageDays: Int, authApiUrl: String, sendDataApiUrl: String)ContextualDataInitiates data collection, sending it to the Fivvy's Analytics Data API.
getDeviceInformationEmptyPromise<IHardwareAttributes>Returns the device hardware information of the customer.
getAppUsageInt 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.
getAppsInstalledEmptyPromise<IInstalledApps[]>Returns an IInstalledApps Array for all the queries in AndroidManifest that user had install in his phone.
openUsageAccessSettings{ln: String, appName: String, appDescription: String, modalText: String, imagePath: byte[], dialogTitle: string, dialogMessage1: String, dialogMessage2: String, blacklist: []null}BooleanOpen settings view with pre-built modal to grant app usage permission.
openUsageAccessSettingsDirectly(blacklist: []null)BooleanOpen settings view without pre-built modal to grant app usage permission.

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,
    forceInit: boolean
 }
`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;
  }

  `getAppUsage return object interface`
  IAppUsage {
    appName: string;
    usage: number;
    packageName: string;
  }
  `getAppsInstalled return object interface`
  IInstalledApps {
    appName?: string;
    packageName: string;
    category?: string;
    installTime?: string;
    lastUpdateTime?: string;
    versionCode?: string;
    versionName?: string;
  }

⚠️ 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.

Terms of use

All content here is the property of Fivvy, it should not be used without their permission.

2.0.2

11 months ago

2.0.1

11 months ago

2.0.0

11 months ago

2.0.0-beta.1

11 months ago

1.1.5

1 year ago

1.1.4

1 year ago

1.1.3

1 year ago

1.1.2

1 year ago

1.1.1

1 year ago

1.1.0

1 year ago

0.5.2

1 year ago