Setup & debugging

These methods are a reference for integrating the OneSignal SDK into your app. For full platform-specific setup instructions, see Mobile SDK setup.

initialize()

Initializes the OneSignal SDK. This should be called during application startup. The ONESIGNAL_APP_ID can be found in Keys & IDs.

If you want to delay initialization of the OneSignal SDK, we recommend using our Privacy methods.

OneSignal.initWithContext(this, ONESIGNAL_APP_ID)

setLogLevel()

Set the logging to print additional logs to Android LogCat or Xcode logs. Call this before initializing OneSignal. See Getting a Debug Log for more details.

// LogLevel: .None | .Fatal | .Error | .Warn | .Info | .Debug | .Verbose
OneSignal.Debug.logLevel = LogLevel.Verbose

setAlertLevel()

Sets the logging level to show as alert dialogs in your app. Make sure to remove this before submitting to the app store.

OneSignal.Debug.alertLevel = LogLevel.Exception

User identity & properties

When users open your app, OneSignal automatically creates a OneSignal ID (user-level) and a Subscription ID (device-level). You can associate multiple subscriptions (e.g., devices, emails, phone numbers) with a single user by calling login() with your unique user identifier.

See Users and Aliases for more details.

login(external_id)

Sets the user context to the provided external_id. Ensures that all Subscriptions and properties associated with this external_id are unified under a single onesignal_id. See Users for more details.

Key behaviors:

  • If the external_id already exists, the SDK switches to that user. Anonymous data collected before login is not merged and will be discarded.
  • If the external_id does not exist, the local state will be saved under the current onesignal_id. Any data collected while the user was anonymous will be kept.
  • SDK retries automatically on network failure or server error.
Call login every time the app identifies a user.
OneSignal.login("external_id")

logout()

Unlinks the current user from the subscription.

  • Removes the external_id from the current push subscription.
  • Resets the OneSignal ID to a new anonymous user.
  • Any new data (e.g tags, Subscriptions, session data, etc.) will now be set on the new anonymous user until they are identified with the login method.
Use this when a user signs out of your app if you want to set the subscription to a new anonymous user.
OneSignal.logout()

getOnesignalId()

Retrieve the current OneSignal ID. May be null if called before user state is initialized. Instead, use User State addObserver() to listen for user state changes.

val id = OneSignal.User.onesignalId

getExternalId()

Retrieve the current External ID. May be null if not set or called before user state is initialized. Instead, use User State addObserver() to listen for user state changes.

  val id = OneSignal.User.externalId

addObserver() user state

Listen for changes in the user context (e.g., login, logout, ID assignment).

OneSignal.User.addObserver(object : IUserStateObserver {
    override fun onUserStateChange(state: UserChangedState) {
        println("User State Changed: onesignalId=${state.current.onesignalId}, externalId=${state.current.externalId}")
    }
})

addAlias(), addAliases(), removeAlias(), removeAliases()

Aliases are alternative identifiers (like usernames or CRM IDs).

  • Set external_id with login() before adding aliases. Aliases added to subscriptions without external_id will not sync across multiple subscriptions.
  • See Aliases for details.
// Add a single alias
OneSignal.User.addAlias("ALIAS_LABEL", "ALIAS_ID")

// Add multiple aliases
var aliases = mapOf("ALIAS_LABEL_01" to "ALIAS_ID_01", "ALIAS_LABEL_02" to "ALIAS_ID_02")
OneSignal.User.addAliases(aliases)

// Remove a single alias
OneSignal.User.removeAlias("ALIAS_LABEL")

// Remove multiple aliases
OneSignal.User.removeAliases(["ALIAS_LABEL_01", "ALIAS_LABEL_02"])

setLanguage()

Overrides the auto-detected language of the user. Use ISO 639-1 language code.

OneSignal.getUser().setLanguage("en");

Data Tags

Tags are custom key : value pairs of string data you set on users based on events or user properties. See Data Tags for more details.

addTag(), addTags()

Set a single or multiple tags on the current user.

  • Values will be replaced if the key already exists.
  • Exceeding your plan’s tag limit will cause the operations to fail silently.
OneSignal.User.addTag("KEY", "VALUE")

OneSignal.User.addTags(mapOf("KEY_01" to "VALUE_01", "KEY_02" to "VALUE_02"))

removeTag(), removeTags()

Delete a single or multiple tags from the current user.

OneSignal.User.removeTag("KEY")

OneSignal.User.removeTags(listOf("KEY_01", "KEY_02"))

getTags()

Returns the local copy of the user’s tags. Tags are updated from the server during login() or new app sessions.

val tags: Map<String, String> = OneSignal.User.getTags()	

Privacy

setConsentRequired()

Enforces user consent before data collection begins. Must be called before initializing the SDK.

OneSignal.consentRequired = true

setConsentGiven()

Grants or revokes user consent for data collection. Without consent, no data is sent to OneSignal and no subscription is created.

  • If setConsentRequired() is true, our SDK will not be fully enabled until setConsentGiven is called with true.
  • If setConsentGiven is set to true and a Subscription is created, then later it is set to false, that Subscription will no longer receive updates. The current data for that Subscription remains unchanged until setConsentGiven is set to true again.
  • If you want to delete the User and/or Subscription data, use our Delete user or Delete subscription APIs.
OneSignal.consentGiven = true

Location

Tracking location points requires 3 steps:

  1. Add location tracking permissions and dependencies to your app.

You may get the following errors:

LocationManager.startGetLocation: not possible, no location dependency found

Check your App’s dependencies. A common solutions is in you app/build.gradle add: implementation 'com.google.android.gms:play-services-location:21.0.1'

  1. Enable your app to share location with OneSignal using the Location.setShared() method.
  2. Request permission from the user for location tracking with the Location.requestPermission method or use in-app messages.

setShared() location

Use this method to allow our SDK to start tracking the Subscription’s latitude and longitude. Make sure you set the proper location permissions in your app first.

// Enable your app to share location with OneSignal
OneSignal.Location.isShared = true

// Returns true if your app is sharing location with OneSignal
var isShared: Boolean = OneSignal.isShared

requestPermission() location

Use this method to display the system-level location permission prompt to your users or instead use in-app messages. Make sure you set the proper location permissions in your app and enabled your app to share location with OneSignal.

// Request location tracking permissions
OneSignal.Location.requestPermission(true)

Subscriptions

See Subscriptions for more details.

User.pushSubscription.id

Returns the current push subscription ID. May return null if called too early. Its recommended to get this data within the subscription observer to react to changes.

val id = OneSignal.User.pushSubscription.id

User.pushSubscription.token

Returns the current push subscription token. May return null if called too early. Its recommended to get this data within the subscription observer to react to changes.

val pushToken = OneSignal.User.subscriptions.push.token

addObserver() push subscription changes

Use this method to respond to push subscription changes like:

  • The device receives a new push token from Google (FCM) or Apple (APNs)
  • OneSignal assigns a subscription ID
  • The optedIn value changes (e.g. called optIn() or optOut())
  • The user toggles push permission in system settings, then opens the app

When this happens, the SDK triggers the onPushSubscriptionChange event. Your listener receives a state object with the previous and current values so you can detect exactly what changed.

To stop listening for updates, call the associated removeObserver() or removeEventListener() method.

class MyObserver : IPushSubscriptionObserver {
  init {
    OneSignal.User.pushSubscription.addObserver(this)
  }
    
  override fun onPushSubscriptionChange(state: PushSubscriptionChangedState) {
    if (state.current.optedIn) {
      println("User is now opted-in with push token: ${state.current.token}")
    }
  }
}

// Remove the observer
OneSignal.User.pushSubscription.removeObserver(this)

optOut(), optIn(), optedIn

Control the subscription status (subscribed or unsubscribed) of the current push Subscription. Use these methods to control the push subscription status within your app. Common use cases: 1) Prevent push from being sent to users that log out. 2) Implement a notification preference center within your app.

  • optOut(): Sets the current push subscription status to unsubscribed (even if the user has a valid push token).
  • optIn(): Does one of three actions:
    1. If the Subscription has a valid push token, it sets the current push subscription status to subscribed.
    2. If the Subscription does not have a valid push token, it displays the push permission prompt.
    3. If the push permission prompt has been displayed more than the operating system’s limit (once iOS, twice Android), it displays the fallback prompt.

Fallback to settings prompt

  • optedIn: Returns true if the current push subscription status is subscribed, otherwise false. If the push token is valid but optOut() was called, this will return false.
OneSignal.User.pushSubscription.optOut()

OneSignal.User.pushSubscription.optIn()

val optedIn = OneSignal.User.subscriptions.push.optedIn

addEmail(), removeEmail()

Adds or removes an email Subscription (email address) to/from the current user. Call addEmail after login() to set the correct user context. Compatible with Identity Verification.

OneSignal.User.addEmail("[example@email.com]")

OneSignal.User.removeEmail("[example@email.com]")

addSms(), removeSms()

Adds or removes an SMS Subscription (phone number) to/from the current user. Requires E.164 format. Call addSms after login() to set the correct user context. Compatible with Identity Verification.

OneSignal.User.addSms("+15558675309")

OneSignal.User.removeSms("+15558675309")

Push permissions

requestPermission(fallbackToSettings) push

Shows the native system prompt asking the user for push notification permission. Optionally enable a fallback prompt that links to the settings app.

  • fallbackToSettings: If true, the fallback prompt will be displayed if the user denied push permissions more than the operating system’s limit (once iOS, twice Android).

Fallback-to-settings prompt when permission is blocked

See Prompt for Push Permissions for more information.

// We recommend removing this method after testing and instead use In-App Messages to prompt for notification permission.
// Passing true will fallback to setting prompt if the user denies push permissions
OneSignal.Notifications.requestPermission(true)

addPermissionObserver() push

Use this method to track push permission changes like:

  • The notification permission prompt is displayed to the user.
  • The user accepts or declines the permission prompt.
  • The user enables or disables notifications for your app in the device’s app settings and then returns to your app.

When this happens, the SDK triggers the onOSPermissionChanged event. Your listener receives a state object with the from and to values so you can detect exactly what changed.

To stop listening for updates, call the associated removePermissionObserver() method.

class MyObserver : IPermissionObserver {
  init {
    OneSignal.Notifications.addPermissionObserver(this)
  }

  override fun onNotificationPermissionChange(granted: Boolean) {
    if (granted) {
      // Notifications are now enabled
    }
  }

  fun cleanup() {
    OneSignal.Notifications.removePermissionObserver(this)
  }
}

getPermission(), getCanRequestPermission()

getPermission() returns the current push permission status at the app-level. It does not consider the OneSignal-level subscription status if you changed it via optOut() or the enabled parameter in the Users and Subscriptions APIs. Instead of using getPermission(), we recommend using the Push Permission Observer to track changes in the device’s notification permission status while the app is running or the Push Subscription Observer to track changes in the push subscription status.

getCanRequestPermission() returns whether attempting to request permission will result in a prompt being displayed to the user. If false, the user has already denied permission and can either be shown the fallback prompt or no prompt at all. See Prompt for push permissions for more information.

// true if the app has permission to display notifications
OneSignal.Notifications.permission

// true if the device can display system notification permission prompt
val canRequest: Boolean = OneSignal.Notifications.canRequestPermission

permissionNative iOS

Returns an enum for the native permission of the iOS device. It will be one of:

  • 0 = NotDetermined
  • 1 = Denied
  • 2 = Authorized
  • 3 = Provisional (only available in iOS 12+)
  • 4 = Ephemeral (only available in iOS 14+)
let permissionNative: OSNotificationPermission = OneSignal.Notifications.permissionNative.rawValue

Push notification events

addClickListener() push

Set a callback that runs when a user clicks a push notification that opens the app.

The app’s activity or scene is already launched by the time this event fires. Use this handler to perform any custom logic — do not relaunch or duplicate app navigation manually.

Use removeClickListener() or removeEventListener() to stop listening when the handler is no longer needed.

val clickListener = object : INotificationClickListener {
  override fun onClick(event: INotificationClickEvent) {
    Log.d("OneSignal", "Notification clicked: ${event.notification.title}")
  }
}
OneSignal.Notifications.addClickListener(clickListener)

addForegroundLifecycleListener() push

Allows you to intercept and control how notifications behave when the app is in the foreground.

By default, OneSignal automatically displays the notification. You can override this behavior using event.preventDefault() to:

  • Suppress the notification
  • Customize it
  • Delay display for async logic (e.g., fetch user state, log events)

Call event.notification.display() to manually show it later.

This runs after Notification Service Extensions, which modify the payload before display.

Use removeForegroundLifecycleListener() or removeEventListener() to stop listening when the handler is no longer needed.

val lifecycleListener = object : INotificationLifecycleListener {
  override fun onWillDisplay(event: INotificationWillDisplayEvent) {
    Log.d("OneSignal", "Foreground notification: ${event.notification.title}")
    // Uncomment to prevent the notification from being displayed while in the foreground
    // event.preventDefault()
  }
}
OneSignal.Notifications.addForegroundLifecycleListener(lifecycleListener)

clearAllNotifications()

Removes all OneSignal notifications from the Notification Shade. Use instead of Android’s android.app.NotificationManager.cancel. Otherwise, the notifications will be restored when your app is restarted.

OneSignal.Notifications.clearAllNotifications()

removeNotification() Android

Cancel a single notification based on its Android notification ID.

Use instead of Android’s android.app.NotificationManager.cancel. Otherwise, the notification will be restored when your app is restarted.

OneSignal.Notifications.removeNotification(id)

removeGroupedNotifications() Android

Cancel a group of OneSignal notifications with the provided group key. Grouping notifications is a OneSignal concept. There is no android.app.NotificationManager equivalent.

OneSignal.Notifications.removeGroupedNotifications("GROUP_KEY")

In-App Messages

In-app messages do not require any code; however, the SDK enables you to customize when messages are presented and handle lifecycle events.

addTrigger(), addTriggers()

Decide when to display an In-App Message based on a single or multiple triggers. See Triggers for more information.

Triggers are not persisted to the backend. They only exist on the local device and apply to the current user.

OneSignal.InAppMessages.addTrigger("KEY", "VALUE")

OneSignal.InAppMessages.addTriggers(mapOf("KEY_01" to "VALUE_01", "KEY_02" to "VALUE_02"))

removeTrigger(), removeTriggers(), clearTriggers()

Remove a single, multiple, or all triggers with the provided key from the current user.

OneSignal.InAppMessages.removeTrigger("KEY")

OneSignal.InAppMessages.removeTriggers(setOf("KEY_01", "KEY_02"))

OneSignal.InAppMessages.clearTriggers()

paused

Prevent In-app messages from being displayed to the user. When set to true, no in-app messages will be presented. When set to false, any messages the user qualifies for will be presented to them at the appropriate time.

OneSignal.InAppMessages.paused = true

addLifecycleListener()

Respond to or track In-App Messages being displayed and dismissed.

val lifecycleListener = object : IInAppMessageLifecycleListener {
  override fun onWillDisplay(event: IInAppMessageWillDisplayEvent) {
    print(event.message.messageId)
  }

  override fun onDidDisplay(event: IInAppMessageDidDisplayEvent) {
    print(event.message.messageId)
  }

  override fun onWillDismiss(event: IInAppMessageWillDismissEvent) {
    print(event.message.messageId)
  }

  override fun onDidDismiss(event: IInAppMessageDidDismissEvent) {
    print(event.message.messageId)
  }
}
OneSignal.InAppMessages.addLifecycleListener(lifecycleListener)
OneSignal.InAppMessages.removeLifecycleListener(lifecycleListener)

addClickListener() in-app

Respond to in-app message click events. The event contains the following click action metadata:

  • actionId: A custom identifier you set on the element.
  • urlTarget: An enum specifying how the launch URL for the message will be presented.
  • url: The launch URL for the action, if any.
  • closingMessage: A boolean value indicating if the action resulted in the message being closed.
val clickListener = object : IInAppMessageClickListener {
  override fun onClick(event: IInAppMessageClickEvent) {
    print(event.result.actionId)
  }
}
OneSignal.InAppMessages.addClickListener(clickListener)

Live Activity

Applications should allow users to opt-in to Live Activities. For example, your app gives the user the option to start the Live Activity within your US using a button or presenting an IAM. You may start and update a Live Activity via any method without an explicit prompt, unlike Notification Permission or Location Permission. Live Activities appear with the iOS Provisional Authorization UI. Live Activities must be started when your application is in the foreground. We recommend reading Apple’s developer guidelines to learn more about Live Activities.

setup()

Allows OneSignal to manage the lifecycle of a LiveActivity on behalf of the application. This includes listening for both pushToStart token updates and pushToUpdate token updates.

//... your app's code 
OneSignal.LiveActivities.setup(MyWidgetAttributes.self);

setupDefault()

Allows cross platform SDK’s to manage the lifecycle of a LiveActivity by eliminating the need for a customer app to define and manage their own ActivityAttributes. See Cross-platform setup for further details.

using OneSignalSDK;

//Push To Start
OneSignal.LiveActivities.SetupDefault();

//Launching the Live Activity from within the app (not needed for push to start)
string activityId = "my_activity_id";

OneSignal.LiveActivities.StartDefault(
  activityId,
  new Dictionary<string, object>() {
      { "title", "Welcome!" }
  },
  new Dictionary<string, object>() {
      { "message", new Dictionary<string, object>() {
          { "en", "Hello World!"}
      }},
  });

enter()

Entering a Live Activity associates an activityId with a Live Activity Temporary Push Token on our server. Specify this identifier when using the Update Live Activities REST API to update one or multiple Live Activities simultaneously.

// ... your app's code 
let activity = try Activity<MyWidgetAttributes>.request(
  attributes: attributes,
  contentState: contentState,
  pushType: .token)
Task {
  for await data in activity.pushTokenUpdates {
      let token = data.map {String(format: "%02x", $0)}.joined()
      // ... required code for entering a live activity
      // Activity ID cannot contain "/" characters
      OneSignal.LiveActivities.enter("ACTIVITY_ID", withToken: token)
  }
}

exit()

Exiting a Live activity deletes the association between an Activity Identifier with the Live Activity push token on our server.

OneSignal.LiveActivities.exit("ACTIVITY_ID")

setPushToStartToken()

Optional “low-level” approach to push to start live activities. Offers fine-grained control over the LiveActivity start and update tokens without altering the ActivityAttribute structure. Additional details available here

if #available(iOS 17.2, *) {
  // Setup an async task to monitor and send pushToStartToken updates to OneSignalSDK.
  Task {
      for try await data in Activity<MyWidgetAttributes>.pushToStartTokenUpdates {
          let token = data.map {String(format: "%02x", $0)}.joined()
          OneSignal.LiveActivities.setPushToStartToken(MyWidgetAttributes.self, withToken: token)
      }
  }
  // Setup an async task to monitor for an activity to be started, for each started activity we
  // can then set up an async task to monitor and send updateToken updates to OneSignalSDK.
  Task {
      for await activity in Activity<MyWidgetAttributes>.activityUpdates {
        Task {
            for await pushToken in activity.pushTokenUpdates {
                let token = pushToken.map {String(format: "%02x", $0)}.joined()
                OneSignal.LiveActivities.enter("my-activity-id", withToken: token)
            }
        }
      }
  }
}

removePushToStartToken()

Called per-activity-type whenever that activity type should no longer be registered against the current subscription

OneSignal.LiveActivities.removePushToStartToken(MyWidgetAttributes.self)

Outcomes

Track actions taken by users and attribute them to messages. See Outcomes for more details.

addOutcome()

Add an outcome with the provided name, captured against the current session.

OneSignal.Session.addOutcome("OUTCOME_NAME")

addUniqueOutcome()

Add a unique outcome with the provided name, captured against the current session.

OneSignal.Session.addUniqueOutcome("OUTCOME_NAME")

addOutcomeWithValue()

Add an outcome with the provided name and value captured against the current session.

OneSignal.Session.addOutcomeWithValue("OUTCOME_NAME", 3.14)

Setup & debugging

These methods are a reference for integrating the OneSignal SDK into your app. For full platform-specific setup instructions, see Mobile SDK setup.

initialize()

Initializes the OneSignal SDK. This should be called during application startup. The ONESIGNAL_APP_ID can be found in Keys & IDs.

If you want to delay initialization of the OneSignal SDK, we recommend using our Privacy methods.

OneSignal.initWithContext(this, ONESIGNAL_APP_ID)

setLogLevel()

Set the logging to print additional logs to Android LogCat or Xcode logs. Call this before initializing OneSignal. See Getting a Debug Log for more details.

// LogLevel: .None | .Fatal | .Error | .Warn | .Info | .Debug | .Verbose
OneSignal.Debug.logLevel = LogLevel.Verbose

setAlertLevel()

Sets the logging level to show as alert dialogs in your app. Make sure to remove this before submitting to the app store.

OneSignal.Debug.alertLevel = LogLevel.Exception

User identity & properties

When users open your app, OneSignal automatically creates a OneSignal ID (user-level) and a Subscription ID (device-level). You can associate multiple subscriptions (e.g., devices, emails, phone numbers) with a single user by calling login() with your unique user identifier.

See Users and Aliases for more details.

login(external_id)

Sets the user context to the provided external_id. Ensures that all Subscriptions and properties associated with this external_id are unified under a single onesignal_id. See Users for more details.

Key behaviors:

  • If the external_id already exists, the SDK switches to that user. Anonymous data collected before login is not merged and will be discarded.
  • If the external_id does not exist, the local state will be saved under the current onesignal_id. Any data collected while the user was anonymous will be kept.
  • SDK retries automatically on network failure or server error.
Call login every time the app identifies a user.
OneSignal.login("external_id")

logout()

Unlinks the current user from the subscription.

  • Removes the external_id from the current push subscription.
  • Resets the OneSignal ID to a new anonymous user.
  • Any new data (e.g tags, Subscriptions, session data, etc.) will now be set on the new anonymous user until they are identified with the login method.
Use this when a user signs out of your app if you want to set the subscription to a new anonymous user.
OneSignal.logout()

getOnesignalId()

Retrieve the current OneSignal ID. May be null if called before user state is initialized. Instead, use User State addObserver() to listen for user state changes.

val id = OneSignal.User.onesignalId

getExternalId()

Retrieve the current External ID. May be null if not set or called before user state is initialized. Instead, use User State addObserver() to listen for user state changes.

  val id = OneSignal.User.externalId

addObserver() user state

Listen for changes in the user context (e.g., login, logout, ID assignment).

OneSignal.User.addObserver(object : IUserStateObserver {
    override fun onUserStateChange(state: UserChangedState) {
        println("User State Changed: onesignalId=${state.current.onesignalId}, externalId=${state.current.externalId}")
    }
})

addAlias(), addAliases(), removeAlias(), removeAliases()

Aliases are alternative identifiers (like usernames or CRM IDs).

  • Set external_id with login() before adding aliases. Aliases added to subscriptions without external_id will not sync across multiple subscriptions.
  • See Aliases for details.
// Add a single alias
OneSignal.User.addAlias("ALIAS_LABEL", "ALIAS_ID")

// Add multiple aliases
var aliases = mapOf("ALIAS_LABEL_01" to "ALIAS_ID_01", "ALIAS_LABEL_02" to "ALIAS_ID_02")
OneSignal.User.addAliases(aliases)

// Remove a single alias
OneSignal.User.removeAlias("ALIAS_LABEL")

// Remove multiple aliases
OneSignal.User.removeAliases(["ALIAS_LABEL_01", "ALIAS_LABEL_02"])

setLanguage()

Overrides the auto-detected language of the user. Use ISO 639-1 language code.

OneSignal.getUser().setLanguage("en");

Data Tags

Tags are custom key : value pairs of string data you set on users based on events or user properties. See Data Tags for more details.

addTag(), addTags()

Set a single or multiple tags on the current user.

  • Values will be replaced if the key already exists.
  • Exceeding your plan’s tag limit will cause the operations to fail silently.
OneSignal.User.addTag("KEY", "VALUE")

OneSignal.User.addTags(mapOf("KEY_01" to "VALUE_01", "KEY_02" to "VALUE_02"))

removeTag(), removeTags()

Delete a single or multiple tags from the current user.

OneSignal.User.removeTag("KEY")

OneSignal.User.removeTags(listOf("KEY_01", "KEY_02"))

getTags()

Returns the local copy of the user’s tags. Tags are updated from the server during login() or new app sessions.

val tags: Map<String, String> = OneSignal.User.getTags()	

Privacy

setConsentRequired()

Enforces user consent before data collection begins. Must be called before initializing the SDK.

OneSignal.consentRequired = true

setConsentGiven()

Grants or revokes user consent for data collection. Without consent, no data is sent to OneSignal and no subscription is created.

  • If setConsentRequired() is true, our SDK will not be fully enabled until setConsentGiven is called with true.
  • If setConsentGiven is set to true and a Subscription is created, then later it is set to false, that Subscription will no longer receive updates. The current data for that Subscription remains unchanged until setConsentGiven is set to true again.
  • If you want to delete the User and/or Subscription data, use our Delete user or Delete subscription APIs.
OneSignal.consentGiven = true

Location

Tracking location points requires 3 steps:

  1. Add location tracking permissions and dependencies to your app.

You may get the following errors:

LocationManager.startGetLocation: not possible, no location dependency found

Check your App’s dependencies. A common solutions is in you app/build.gradle add: implementation 'com.google.android.gms:play-services-location:21.0.1'

  1. Enable your app to share location with OneSignal using the Location.setShared() method.
  2. Request permission from the user for location tracking with the Location.requestPermission method or use in-app messages.

setShared() location

Use this method to allow our SDK to start tracking the Subscription’s latitude and longitude. Make sure you set the proper location permissions in your app first.

// Enable your app to share location with OneSignal
OneSignal.Location.isShared = true

// Returns true if your app is sharing location with OneSignal
var isShared: Boolean = OneSignal.isShared

requestPermission() location

Use this method to display the system-level location permission prompt to your users or instead use in-app messages. Make sure you set the proper location permissions in your app and enabled your app to share location with OneSignal.

// Request location tracking permissions
OneSignal.Location.requestPermission(true)

Subscriptions

See Subscriptions for more details.

User.pushSubscription.id

Returns the current push subscription ID. May return null if called too early. Its recommended to get this data within the subscription observer to react to changes.

val id = OneSignal.User.pushSubscription.id

User.pushSubscription.token

Returns the current push subscription token. May return null if called too early. Its recommended to get this data within the subscription observer to react to changes.

val pushToken = OneSignal.User.subscriptions.push.token

addObserver() push subscription changes

Use this method to respond to push subscription changes like:

  • The device receives a new push token from Google (FCM) or Apple (APNs)
  • OneSignal assigns a subscription ID
  • The optedIn value changes (e.g. called optIn() or optOut())
  • The user toggles push permission in system settings, then opens the app

When this happens, the SDK triggers the onPushSubscriptionChange event. Your listener receives a state object with the previous and current values so you can detect exactly what changed.

To stop listening for updates, call the associated removeObserver() or removeEventListener() method.

class MyObserver : IPushSubscriptionObserver {
  init {
    OneSignal.User.pushSubscription.addObserver(this)
  }
    
  override fun onPushSubscriptionChange(state: PushSubscriptionChangedState) {
    if (state.current.optedIn) {
      println("User is now opted-in with push token: ${state.current.token}")
    }
  }
}

// Remove the observer
OneSignal.User.pushSubscription.removeObserver(this)

optOut(), optIn(), optedIn

Control the subscription status (subscribed or unsubscribed) of the current push Subscription. Use these methods to control the push subscription status within your app. Common use cases: 1) Prevent push from being sent to users that log out. 2) Implement a notification preference center within your app.

  • optOut(): Sets the current push subscription status to unsubscribed (even if the user has a valid push token).
  • optIn(): Does one of three actions:
    1. If the Subscription has a valid push token, it sets the current push subscription status to subscribed.
    2. If the Subscription does not have a valid push token, it displays the push permission prompt.
    3. If the push permission prompt has been displayed more than the operating system’s limit (once iOS, twice Android), it displays the fallback prompt.

Fallback to settings prompt

  • optedIn: Returns true if the current push subscription status is subscribed, otherwise false. If the push token is valid but optOut() was called, this will return false.
OneSignal.User.pushSubscription.optOut()

OneSignal.User.pushSubscription.optIn()

val optedIn = OneSignal.User.subscriptions.push.optedIn

addEmail(), removeEmail()

Adds or removes an email Subscription (email address) to/from the current user. Call addEmail after login() to set the correct user context. Compatible with Identity Verification.

OneSignal.User.addEmail("[example@email.com]")

OneSignal.User.removeEmail("[example@email.com]")

addSms(), removeSms()

Adds or removes an SMS Subscription (phone number) to/from the current user. Requires E.164 format. Call addSms after login() to set the correct user context. Compatible with Identity Verification.

OneSignal.User.addSms("+15558675309")

OneSignal.User.removeSms("+15558675309")

Push permissions

requestPermission(fallbackToSettings) push

Shows the native system prompt asking the user for push notification permission. Optionally enable a fallback prompt that links to the settings app.

  • fallbackToSettings: If true, the fallback prompt will be displayed if the user denied push permissions more than the operating system’s limit (once iOS, twice Android).

Fallback-to-settings prompt when permission is blocked

See Prompt for Push Permissions for more information.

// We recommend removing this method after testing and instead use In-App Messages to prompt for notification permission.
// Passing true will fallback to setting prompt if the user denies push permissions
OneSignal.Notifications.requestPermission(true)

addPermissionObserver() push

Use this method to track push permission changes like:

  • The notification permission prompt is displayed to the user.
  • The user accepts or declines the permission prompt.
  • The user enables or disables notifications for your app in the device’s app settings and then returns to your app.

When this happens, the SDK triggers the onOSPermissionChanged event. Your listener receives a state object with the from and to values so you can detect exactly what changed.

To stop listening for updates, call the associated removePermissionObserver() method.

class MyObserver : IPermissionObserver {
  init {
    OneSignal.Notifications.addPermissionObserver(this)
  }

  override fun onNotificationPermissionChange(granted: Boolean) {
    if (granted) {
      // Notifications are now enabled
    }
  }

  fun cleanup() {
    OneSignal.Notifications.removePermissionObserver(this)
  }
}

getPermission(), getCanRequestPermission()

getPermission() returns the current push permission status at the app-level. It does not consider the OneSignal-level subscription status if you changed it via optOut() or the enabled parameter in the Users and Subscriptions APIs. Instead of using getPermission(), we recommend using the Push Permission Observer to track changes in the device’s notification permission status while the app is running or the Push Subscription Observer to track changes in the push subscription status.

getCanRequestPermission() returns whether attempting to request permission will result in a prompt being displayed to the user. If false, the user has already denied permission and can either be shown the fallback prompt or no prompt at all. See Prompt for push permissions for more information.

// true if the app has permission to display notifications
OneSignal.Notifications.permission

// true if the device can display system notification permission prompt
val canRequest: Boolean = OneSignal.Notifications.canRequestPermission

permissionNative iOS

Returns an enum for the native permission of the iOS device. It will be one of:

  • 0 = NotDetermined
  • 1 = Denied
  • 2 = Authorized
  • 3 = Provisional (only available in iOS 12+)
  • 4 = Ephemeral (only available in iOS 14+)
let permissionNative: OSNotificationPermission = OneSignal.Notifications.permissionNative.rawValue

Push notification events

addClickListener() push

Set a callback that runs when a user clicks a push notification that opens the app.

The app’s activity or scene is already launched by the time this event fires. Use this handler to perform any custom logic — do not relaunch or duplicate app navigation manually.

Use removeClickListener() or removeEventListener() to stop listening when the handler is no longer needed.

val clickListener = object : INotificationClickListener {
  override fun onClick(event: INotificationClickEvent) {
    Log.d("OneSignal", "Notification clicked: ${event.notification.title}")
  }
}
OneSignal.Notifications.addClickListener(clickListener)

addForegroundLifecycleListener() push

Allows you to intercept and control how notifications behave when the app is in the foreground.

By default, OneSignal automatically displays the notification. You can override this behavior using event.preventDefault() to:

  • Suppress the notification
  • Customize it
  • Delay display for async logic (e.g., fetch user state, log events)

Call event.notification.display() to manually show it later.

This runs after Notification Service Extensions, which modify the payload before display.

Use removeForegroundLifecycleListener() or removeEventListener() to stop listening when the handler is no longer needed.

val lifecycleListener = object : INotificationLifecycleListener {
  override fun onWillDisplay(event: INotificationWillDisplayEvent) {
    Log.d("OneSignal", "Foreground notification: ${event.notification.title}")
    // Uncomment to prevent the notification from being displayed while in the foreground
    // event.preventDefault()
  }
}
OneSignal.Notifications.addForegroundLifecycleListener(lifecycleListener)

clearAllNotifications()

Removes all OneSignal notifications from the Notification Shade. Use instead of Android’s android.app.NotificationManager.cancel. Otherwise, the notifications will be restored when your app is restarted.

OneSignal.Notifications.clearAllNotifications()

removeNotification() Android

Cancel a single notification based on its Android notification ID.

Use instead of Android’s android.app.NotificationManager.cancel. Otherwise, the notification will be restored when your app is restarted.

OneSignal.Notifications.removeNotification(id)

removeGroupedNotifications() Android

Cancel a group of OneSignal notifications with the provided group key. Grouping notifications is a OneSignal concept. There is no android.app.NotificationManager equivalent.

OneSignal.Notifications.removeGroupedNotifications("GROUP_KEY")

In-App Messages

In-app messages do not require any code; however, the SDK enables you to customize when messages are presented and handle lifecycle events.

addTrigger(), addTriggers()

Decide when to display an In-App Message based on a single or multiple triggers. See Triggers for more information.

Triggers are not persisted to the backend. They only exist on the local device and apply to the current user.

OneSignal.InAppMessages.addTrigger("KEY", "VALUE")

OneSignal.InAppMessages.addTriggers(mapOf("KEY_01" to "VALUE_01", "KEY_02" to "VALUE_02"))

removeTrigger(), removeTriggers(), clearTriggers()

Remove a single, multiple, or all triggers with the provided key from the current user.

OneSignal.InAppMessages.removeTrigger("KEY")

OneSignal.InAppMessages.removeTriggers(setOf("KEY_01", "KEY_02"))

OneSignal.InAppMessages.clearTriggers()

paused

Prevent In-app messages from being displayed to the user. When set to true, no in-app messages will be presented. When set to false, any messages the user qualifies for will be presented to them at the appropriate time.

OneSignal.InAppMessages.paused = true

addLifecycleListener()

Respond to or track In-App Messages being displayed and dismissed.

val lifecycleListener = object : IInAppMessageLifecycleListener {
  override fun onWillDisplay(event: IInAppMessageWillDisplayEvent) {
    print(event.message.messageId)
  }

  override fun onDidDisplay(event: IInAppMessageDidDisplayEvent) {
    print(event.message.messageId)
  }

  override fun onWillDismiss(event: IInAppMessageWillDismissEvent) {
    print(event.message.messageId)
  }

  override fun onDidDismiss(event: IInAppMessageDidDismissEvent) {
    print(event.message.messageId)
  }
}
OneSignal.InAppMessages.addLifecycleListener(lifecycleListener)
OneSignal.InAppMessages.removeLifecycleListener(lifecycleListener)

addClickListener() in-app

Respond to in-app message click events. The event contains the following click action metadata:

  • actionId: A custom identifier you set on the element.
  • urlTarget: An enum specifying how the launch URL for the message will be presented.
  • url: The launch URL for the action, if any.
  • closingMessage: A boolean value indicating if the action resulted in the message being closed.
val clickListener = object : IInAppMessageClickListener {
  override fun onClick(event: IInAppMessageClickEvent) {
    print(event.result.actionId)
  }
}
OneSignal.InAppMessages.addClickListener(clickListener)

Live Activity

Applications should allow users to opt-in to Live Activities. For example, your app gives the user the option to start the Live Activity within your US using a button or presenting an IAM. You may start and update a Live Activity via any method without an explicit prompt, unlike Notification Permission or Location Permission. Live Activities appear with the iOS Provisional Authorization UI. Live Activities must be started when your application is in the foreground. We recommend reading Apple’s developer guidelines to learn more about Live Activities.

setup()

Allows OneSignal to manage the lifecycle of a LiveActivity on behalf of the application. This includes listening for both pushToStart token updates and pushToUpdate token updates.

//... your app's code 
OneSignal.LiveActivities.setup(MyWidgetAttributes.self);

setupDefault()

Allows cross platform SDK’s to manage the lifecycle of a LiveActivity by eliminating the need for a customer app to define and manage their own ActivityAttributes. See Cross-platform setup for further details.

using OneSignalSDK;

//Push To Start
OneSignal.LiveActivities.SetupDefault();

//Launching the Live Activity from within the app (not needed for push to start)
string activityId = "my_activity_id";

OneSignal.LiveActivities.StartDefault(
  activityId,
  new Dictionary<string, object>() {
      { "title", "Welcome!" }
  },
  new Dictionary<string, object>() {
      { "message", new Dictionary<string, object>() {
          { "en", "Hello World!"}
      }},
  });

enter()

Entering a Live Activity associates an activityId with a Live Activity Temporary Push Token on our server. Specify this identifier when using the Update Live Activities REST API to update one or multiple Live Activities simultaneously.

// ... your app's code 
let activity = try Activity<MyWidgetAttributes>.request(
  attributes: attributes,
  contentState: contentState,
  pushType: .token)
Task {
  for await data in activity.pushTokenUpdates {
      let token = data.map {String(format: "%02x", $0)}.joined()
      // ... required code for entering a live activity
      // Activity ID cannot contain "/" characters
      OneSignal.LiveActivities.enter("ACTIVITY_ID", withToken: token)
  }
}

exit()

Exiting a Live activity deletes the association between an Activity Identifier with the Live Activity push token on our server.

OneSignal.LiveActivities.exit("ACTIVITY_ID")

setPushToStartToken()

Optional “low-level” approach to push to start live activities. Offers fine-grained control over the LiveActivity start and update tokens without altering the ActivityAttribute structure. Additional details available here

if #available(iOS 17.2, *) {
  // Setup an async task to monitor and send pushToStartToken updates to OneSignalSDK.
  Task {
      for try await data in Activity<MyWidgetAttributes>.pushToStartTokenUpdates {
          let token = data.map {String(format: "%02x", $0)}.joined()
          OneSignal.LiveActivities.setPushToStartToken(MyWidgetAttributes.self, withToken: token)
      }
  }
  // Setup an async task to monitor for an activity to be started, for each started activity we
  // can then set up an async task to monitor and send updateToken updates to OneSignalSDK.
  Task {
      for await activity in Activity<MyWidgetAttributes>.activityUpdates {
        Task {
            for await pushToken in activity.pushTokenUpdates {
                let token = pushToken.map {String(format: "%02x", $0)}.joined()
                OneSignal.LiveActivities.enter("my-activity-id", withToken: token)
            }
        }
      }
  }
}

removePushToStartToken()

Called per-activity-type whenever that activity type should no longer be registered against the current subscription

OneSignal.LiveActivities.removePushToStartToken(MyWidgetAttributes.self)

Outcomes

Track actions taken by users and attribute them to messages. See Outcomes for more details.

addOutcome()

Add an outcome with the provided name, captured against the current session.

OneSignal.Session.addOutcome("OUTCOME_NAME")

addUniqueOutcome()

Add a unique outcome with the provided name, captured against the current session.

OneSignal.Session.addUniqueOutcome("OUTCOME_NAME")

addOutcomeWithValue()

Add an outcome with the provided name and value captured against the current session.

OneSignal.Session.addOutcomeWithValue("OUTCOME_NAME", 3.14)