OneSignal Android SDK

repository·main·Indexed 20 days ago

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

A plugin for native Android and Amazon applications to integrate email, SMS, push notifications, and in-app messaging. The SDK supports GMS (FCM) and Huawei HMS product flavors, provides user-centric APIs in v5.x.x, and includes features for identity verification via JWT and custom notification sounds.

Tokens
5.7K
Snippets
18
Records
31
Agent score
71%

What's inside OneSignal Android SDK

  1. Important constraints and limitations in OneSignal v5

    main

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

    • App ID: Changing the App ID is not supported.
    • User Namespace Timing: All calls within the User namespace (e.g., OneSignal.User.addTag(...)) must be invoked after the SDK has been initialized.
    • User State Refresh: User state is only refreshed from the 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 is intended behavior.
  2. Understand the OneSignal v5 User-Centered Model

    main

    In v5, OneSignal shifted from a device-centered model (using 'players') to a user-centered model. This model uses three core concepts:

    1. Users: Represents your end-user. A user can have zero or more subscriptions and can be uniquely identified by one or more aliases.
    2. Subscriptions: Refers to the communication channels (Push, In-App Messages, SMS, Email) used to reach 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. The alias label is the key (e.g., external_id), and the alias id is the user-specific value. OneSignal uses a built-in external_id label to support existing external user ID workflows.
  3. Choose between GMS and Huawei product flavors

    main

    The Android demo provides two product flavors to support different device ecosystems:

    • gms: For devices with Google Play Services (FCM). It includes play-services-location. Note that OneSignal initializes its own Firebase app, so you do not need a google-services.json file or the Google Services plugin.
    • huawei: For devices using Huawei HMS. It applies com.huawei.agconnect, excludes GMS dependencies, and includes com.huawei.hms:push and com.huawei.hms:location.

    The Huawei configuration is applied at configuration time based on the Gradle task requested.

  4. Understand the Android Demo State Management architecture

    main

    Unlike the shared guide, the Android demo implements a repository pattern to manage state and SDK interactions:

    • MainApplication.kt: Initializes the SDK before UI rendering. It restores cached state (consent, IAM-paused, location-shared) and registers lifecycle listeners for In-App Messages and Notifications (using event.preventDefault() to allow for async display testing).
    • MainViewModel: The central state holder using LiveData<T>. It implements several OneSignal observer interfaces (IPushSubscriptionObserver, IPermissionObserver, IUserStateObserver, IUserJwtInvalidatedListener) and manages a fetchRequestSequence to prevent stale data from overwriting newer results during API calls.
    • OneSignalRepository.kt: Provides a layer between the ViewModel and the SDK. Some methods are suspend and use Dispatchers.IO, while others are synchronous wrappers.
    • OneSignalService.kt: A REST API client for interacting with OneSignal services.
    • SharedPreferenceUtil.kt: Manages persistent storage for consent, user IDs, location sharing status, IAM pause status, and cached JWT tokens.
  5. Configure OneSignal App ID and Channel ID via local.properties

    main

    The demo uses examples/demo/local.properties to manage environment-specific variables. This file acts similarly to a .env file and is gitignored by default.

    1. Copy local.properties.example to local.properties.
    2. Fill in the following keys:
    KeyPurpose
    ONESIGNAL_APP_IDUsed by MainApplication.onCreate and MainViewModel.loadInitialState to identify your app.
    ONESIGNAL_ANDROID_CHANNEL_IDUsed by OneSignalService.sendNotification when sending payloads with sound.

    Precedence Rules: Values are resolved in this order:

    1. CLI arguments (-PKEY=value)
    2. local.properties
    3. Built-in defaults

    These values are surfaced in your code via BuildConfig.ONESIGNAL_APP_ID and BuildConfig.ONESIGNAL_ANDROID_CHANNEL_ID.

    ONESIGNAL_APP_ID=
    ONESIGNAL_ANDROID_CHANNEL_ID=
  6. Configure OneSignal App ID via local.properties

    main

    You can override the OneSignal App ID using local.properties (which acts as the Android equivalent of .env). The demo app reads BuildConfig.ONESIGNAL_APP_ID on every launch, so changes to this value only require a rebuild.

    Note: Because the SDK itself maintains internal state, if you swap App IDs during testing, you should perform a clean uninstall to clear the SDK's cached data:

    ./gradlew :app:uninstallGmsDebug
    # Clear SDK state when swapping App IDs
    ./gradlew :app:uninstallGmsDebug
  7. Build and run the OneSignal Android Sample App

    main

    The OneSignal Android Sample App is located in the examples/demo/ directory. For the easiest testing experience, use the standalone build located in examples/demo/ rather than building from the SDK root.

    Default Build

    By default, the project is configured to run with the gms (Google Mobile Services) flavor.

    Building from the SDK Root

    If you are building from the OneSignalSDK/ directory instead of the standalone demo directory, you must pass the -PSDK_VERSION flag to specify which version of the SDK to use.

    ./gradlew :app:assembleDebug -PSDK_VERSION=5.9.8
    # Building from the SDK root requires specifying the SDK version
    ./gradlew :app:assembleDebug -PSDK_VERSION=X.Y.Z
  8. Configure the OneSignal App ID

    main

    The Red App uses a default App ID (77e32082-ea27-42e3-a898-c72e141824ef). To use your own OneSignal App ID:

    1. Copy examples/demo/local.properties.example to examples/demo/local.properties.
    2. Set the ONESIGNAL_APP_ID key to your actual App ID:
      ONESIGNAL_APP_ID=YOUR_APP_ID_HERE
    3. Alternatively, pass it via the Gradle CLI:
      ./gradlew :app:installGmsDebug -PONESIGNAL_APP_ID=YOUR_APP_ID_HERE

    Values are read from BuildConfig.ONESIGNAL_APP_ID at launch, so no uninstallation is required after changing the ID.

    ONESIGNAL_APP_ID=YOUR_APP_ID_HERE
  9. Android Best Practices for OneSignal Integration

    main

    When working with the OneSignal Android SDK or the sample app, follow these best practices:

    • Minification: Always keep isMinifyEnabled = true on release build types. This ensures R8 and the SDK's published ProGuard rules are exercised, preventing regressions.
    • Loading States: Avoid using a global LoadingOverlay. Loading should be handled per-section to align with recommended UI patterns.
    • Testing/Automation: When adding new interactive elements or sections, assign a testTag following the {sectionKey}_* pattern. This ensures compatibility with cross-platform Appium tests located in sdk-shared/appium/tests/.
  10. Install OneSignal Android SDK v5

    main

    To include the full OneSignal SDK in your Android project, add the following dependency to your build.gradle.kts (Kotlin) or build.gradle (Groovy) file.

    For greater flexibility, you can also include individual modules:

    • com.onesignal:core: Required core module.
    • com.onesignal:notifications: For notification functionality.
    • com.onesignal:in-app-messages: For in-app message functionality.
    • com.onesignal:location: For location-based functionality.
    // in app/build.gradle.kts
    implementation("com.onesignal:OneSignal:[5.1.6, 5.1.99]")
    // in app/build.gradle
    implementation 'com.onesignal:OneSignal:[5.1.6, 5.1.99]'
  11. Implement Huawei HMS Support

    main

    For devices using Huawei Mobile Services (HMS), you must implement a flavor that includes the HmsMessageServiceAppLevel service. This service acts as a bridge, forwarding HMS messages to the OneSignal SDK.

    Key requirements:

    • Declare HmsMessageServiceAppLevel in your AndroidManifest.xml.
    • Implement a subclass of HmsMessageService that forwards messages to OneSignal.
    • Ensure agconnect-services.json is correctly configured for your package name.