OneSignal Unity SDK

repository·main·Indexed 42 days ago

https://github.com/onesignal/onesignal-unity-sdk

Omni-channel messaging capabilities for mobile applications built with the Unity engine, including Push Notifications, In-App Messages, SMS, and Email. Version 5.3.4 provides tools for Android notification icon customization and dependency management via EDM4U.

Tokens
26.3K
Snippets
58
Records
115
Agent score
52%

What's inside OneSignal

  1. What is External Dependency Manager for Unity (EDM4U)?

    main

    The External Dependency Manager for Unity (EDM4U), formerly known as Play Services Resolver, is a tool used by Unity plugins to manage platform-specific dependencies and versioning. It solves common integration issues by providing:

    • Android Dependency Management: Automatically downloads and integrates Android libraries (AARs/JARs) from Maven repositories and resolves conflicts between plugins.
    • iOS Dependency Management: Integrates with CocoaPods to manage iOS libraries and frameworks in the Xcode project generated by Unity.
    • Package Manager (PM) Registry Setup: Automatically installs PM package registries when a .unitypackage is imported.
    • Unity Plugin Version Management: Uses a Version Handler to ensure that if multiple plugins include different versions of the same dependency (like EDM4U itself), the latest version is activated, preventing conflicts.
  2. Understand the OneSignal Unity Sample App structure

    main

    The sample app follows a structured architecture for managing OneSignal features and UI. Key components include:

    • AppBootstrapper.cs: A persistent entry point that survives scene loads.
    • OneSignalApiService.cs: Handles REST API interactions.
    • AppViewModel.cs: Manages application state and provides a single OnStateChanged event for UI updates.
    • SectionBuilder.cs: Dynamically builds UI sections in C# rather than using individual UXML files for every section.
    • UI/Screens/: Contains empty UXML containers (HomeScreen.uxml, SecondaryScreen.uxml) that are populated by screen controllers.

    This structure separates business logic (Services/ViewModels) from the presentation layer (UI/Controllers).

  3. Understand Android Notification Icons

    main

    Android supports two types of notification icons for OneSignal:

    1. Small Notification Icons: Displayed in the top status bar and on the notification itself. By default, OneSignal uses a bell icon. It is highly recommended to customize this so users recognize your app.
      • Note: Android only uses the alpha channel for these icons. They will appear monochrome in the status bar, though an accent color can be applied to the notification body.
    2. Large Notification Icons: Displayed to the left of text (Android 4.0.3 - 6.0) or to the right (Android 7.0+). If not explicitly set, the small icon is used as a fallback. OneSignal automatically scales these to prevent cropping.

    Recommended Large Icon Size: 256x256 pixels.

  4. Configure Android Resolver settings for AAR explosion and ABI stripping

    main

    The Android Resolver uses 'AAR explosion' (unpacking AAR files) to perform two critical tasks:

    1. Android Manifest Variable Processing: Replacing ${applicationId} with the project's bundleID in AndroidManifest.xml files (required for Unity's Internal Build System).
    2. ABI Stripping: Removing unused native libraries (.so files) to reduce APK size and prevent architecture mismatch errors.

    Note: If you are exporting your project to be built with Gradle or Android Studio, you should disable AAR explosion via the settings menu to allow Gradle to handle these processes natively.

    Settings Location: Assets > External Dependency Manager > Android Resolver > Settings

  5. Disable the OneSignal Location Module

    main

    If your app does not use location features, you can exclude the native location module to reduce build size.

    Note: When disabled, OneSignal.Location.RequestPermission() and OneSignal.Location.IsShared = ... become no-ops, and OneSignal.Location.IsShared will always return false.

    Methods to disable:

    • Editor Toggle: Enable Project Settings > OneSignal > Disable Location Module in the Unity Editor. This setting is saved in ProjectSettings/OneSignalSettings.json.
    • Environment Variable (CI/CD): Set ONESIGNAL_DISABLE_LOCATION=true (or 1) in your environment before running Unity.

    Important: When toggling this flag, you must clear stale native outputs (Xcode projects, CocoaPods/Gradle caches, and prior Build/ artifacts) to ensure the module is fully removed.

    ONESIGNAL_DISABLE_LOCATION=true /path/to/Unity -batchmode -quit -projectPath . -buildTarget iOS -executeMethod BuildScript.BuildiOSSimulator
  6. Handle Android AAR explosion and ABI stripping

    main

    The Android Resolver can 'explode' AAR files (unpacking them into folders) to perform specific tasks:

    • Android Manifest Variable Processing: Replaces ${applicationId} with the project's bundleID in AndroidManifest.xml. This is necessary for Unity's Internal Build System.
    • ABI Stripping: Removes unused native libraries (.so files) for architectures not targeted by the current build to reduce APK size and prevent runtime errors caused by mixed architectures.

    Note: You should disable AAR explosion via Assets > External Dependency Manager > Android Resolver > Settings if you are exporting the project to be built with Gradle or Android Studio externally.

  7. Configure Android Resolver resolution strategies

    main

    The Android Resolver supports two main strategies via Assets > External Dependency Manager > Android Resolver > Settings:

    1. Download Artifacts with Gradle (Default):

      • Removes previous resolution results from Plugins/Android.
      • Collects dependencies from *Dependencies.xml files.
      • Runs download_artifacts.gradle to resolve conflicts and download AARs/JARs.
      • Processes AARs (e.g., patching applicationId in AndroidManifest.xml with the project's bundle ID).
      • Moves processed files to Plugins/Android.
    2. Integrate into mainTemplate.gradle (Patch mainTemplate.gradle):

      • Used when the Patch mainTemplate.gradle setting is enabled.
      • Instead of downloading files to Plugins/Android, it injects repositories and dependencies directly into the project's mainTemplate.gradle.
      • It uses specific markers/patterns to inject code: // Android Resolver * Start / // Android Resolver * End, // Android Resolver Repos Start / // Android Resolver Repos End, // Android Resolver Dependencies Start / // Android Resolver Dependencies End, and the ***DEPS*** pattern.
  8. How the Version Handler works

    main

    The Version Handler component manages shared Unity plugin dependencies, upgrades, and uninstalls. It works by modifying Unity asset metadata (.meta files), which means it does not work with Package Manager installed packages. If EDM4U is included in a PM package, the Version Handler component will remain inactive for those plugins.

    Core Capabilities:

    • Upgrading: Automatically checks assets to determine if they are out of date and cleans up old files.
    • Uninstallation: Removes plugins distributed with manifest files.
    • Restoration: Can restore assets to their original install locations if they are tagged with the exportpath label.
  9. Restore SDK state from persistence

    main

    To provide a seamless user experience, you should persist OneSignal configuration settings (like consent and IAM pause status) using PlayerPrefs or a similar service.

    The correct restoration order is critical:

    1. Before Initialize: Restore OneSignal.ConsentRequired and OneSignal.ConsentGiven.
    2. Call OneSignal.Initialize(appId).
    3. After Initialize: Restore settings that depend on an active session, such as OneSignal.InAppMessages.Paused and OneSignal.Location.IsShared.
    // Example: Subscribing to In-App Message events
    OneSignal.InAppMessages.WillDisplay += handler;
    
    // Example: Subscribing to User/Subscription observers
    OneSignal.User.PushSubscription.Changed += handler;
    
    // Remember to unsubscribe in OnDestroy()
    // OneSignal.User.PushSubscription.Changed -= handler;"}, {
  10. Understand OneSignal SDK limitations and behavior

    main

    When using the OneSignal Unity SDK, be aware of the following operational constraints:

    • App IDs: Changing the App ID is not supported.
    • User Namespace: All calls within the OneSignal.User namespace (e.g., OneSignal.User.AddTag("tag", "value")) must be invoked after the SDK has been initialized.
    • User State Refresh: To optimize performance, the SDK only refreshes user state from the server during a new session (a cold start or when the app has been in the background for more than 30 seconds) or when the user logs in.
  11. Understand the User-Centered Model (v5.x.x)

    main

    In OneSignal SDK v5.x.x, the architecture has shifted from a device-centered model to a user-centered model. This replaces the legacy 'player' concept with three core abstractions:

    1. Users: Represents the end-user. A user can have multiple subscriptions and can be uniquely identified by one or more aliases. Users can also have data tags for attribution.
    2. Subscriptions: Refers to the communication channels (Push, In-App Messages, SMS, Email) used by a user. A subscription is the successor to the legacy 'player' concept. Each subscription has a subscription_id (formerly player_id).
    3. Aliases: Key-value pairs used to identify a user across different systems. The alias label is the key (e.g., external_id) and the alias id is the value specific to that user. OneSignal provides a built-in external_id label to support existing External User ID workflows.
  12. Understand OneSignal User Namespace and State Lifecycle

    main

    In the OneSignal Unity SDK, certain operations follow specific lifecycle and architectural rules:

    • User Namespace Calls: Any calls made to the OneSignal.User namespace (e.g., OneSignal.User.AddTag("tag", "2")) must be invoked after the SDK has been initialized.
    • User State Refresh: The user state is only refreshed from the OneSignal server during a new session (a cold start or when the app has been in the background for over 30 seconds) or when the user logs in. This behavior is intentional.
    • App ID Constraints: Changing the App ID after setup is not supported.