The methods below require the OneSignal SDK versions 3 & 4.

It is recommended to upgrade to our latest version 5 SDKs for User Model APIs.

See Update to User Model for migration steps.

Initializing OneSignal

These methods serve as a reference and are just a single step in the set up process. Make sure to follow the steps for your particular configuration here:

//See Android SDK Setup for details https://documentation.onesignal.com/docs/android-sdk-setup
OneSignal.initWithContext(this);
OneSignal.setAppId(ONESIGNAL_APP_ID);

We have a number of SDK’s with multiple options for initialization within. If you don’t see an init method listed for your particular environment, please follow the links above!

Debugging

setLogLevel Method

Enable logging to help debug if you run into an issue setting up OneSignal. This selector is static, so you can call it before OneSignal init. For websites see Debugging with Browser Tools.

ParametersTypeDescription
logLevelLOG_LEVELSets the logging level to print to the Android LogCat log or Xcode log.
visualLevelLOG_LEVELSets the logging level to show as alert dialogs.
//The following options are available with increasingly more information:
//NONE, FATAL, ERROR, WARN, INFO, DEBUG, VERBOSE
OneSignal.setLogLevel(OneSignal.LOG_LEVEL.VERBOSE, OneSignal.LOG_LEVEL.NONE);

External User Ids

OneSignal creates and stores device & channel level data under a unique OneSignal Id called the subscription_id (formerly calledplayer_id). A single user can have multiple subscription_id records based on how many devices, email addresses, and phone numbers they use to interact with your app/site.

You can combine subscription_id records in OneSignal under a unique User Id called the external_id.

See the External User Ids guide for more details.

If you have a backend server, we strongly recommend using Identity Verification with your users. Your backend can generate an identifier authentication token and send it to your site.

The OneSignal SDK setExternalUserId method should be called when the user logs into the app/site and within the callback of the setEmail and setSMSNumber methods to link the records together.

let externalUserId = "123456789"; // You will supply the external user id to the OneSignal SDK

OneSignal.push(function() {
  OneSignal.setExternalUserId(externalUserId);
});

If you have a backend server, we strongly recommend using Identity Verification with your users. Your backend can generate an identifier authentication token and send it to your site.

The OneSignal Android SDKs leverage cacheing on external_user_id and Data Tags.

If setting external_user_id through the Edit device API Endpoint, then use the same endpoint to remove the external_user_id upon the user logging out of the app.

The removeExternalUserId method will not work unless the external_user_id is set first with the setExternalUserId method on Android.

This is only applicable on the OneSignal Android Mobile App SDKs.


Tags

Data Tags are custom key : value pairs of string or number data you set on users based on events or user data of your choosing. See Data Tags Overview for more details on what tags are used for.

See Data Tag Implementation for SDK Method details.


User Data

Methods to get the OneSignal Subscription ID, subscription status, prompt status and push token.

Use addPermissionObserver or addSubscriptionObserver to react to changes. For example, update your server when the user becomes subscribed or unsubscribed, and to get the OneSignal Subscription Id.

If you need to store the OneSignal Subscription Id within your backend, you can make a REST API call directly from the observer’s callback. The OneSignal observer fires only when there is a change (including not firing even if the app has been restarted). This helps ensure you are not making unnecessary network calls to your backend on each app restart if nothing changed.

Getting User Properties

Push Notification Properties

If getDeviceState() is called too early it will be null or no available. Use to load your UI to the correct state. Such as showing a toggle button to enable notifications.

// Returns an `OSDeviceState` object with the current immediate device state info
OSDeviceState device = OneSignal.getDeviceState(); 

//Get the OneSignal Push Subscription Id
String userId = device.getUserId();

//Get device's push token identifier
String getPushToken = device.getPushToken();

//Get whether notifications are enabled on the device at the app level
boolean areNotificationsEnabled = device.areNotificationsEnabled();

//The device's push subscription status
boolean isSubscribed = device.isSubscribed();

//Returns value of pushDisabled method
boolean isPushDisabled = device.isPushDisabled();

Notification Permission Statuses

NameStatus
0 - Not DeterminedThe user hasn’t yet made a choice about whether the app is allowed to schedule notifications.
1 - DeniedThe application is not authorized to post user notifications.
2 - AuthorizedThe application is authorized to post user notifications.
3 - ProvisionalThe application is provisionally authorized to post noninterruptive user notifications.
4 - EphemeralFor App Clips. The app is authorized to schedule or receive notifications for a limited amount of time.

Email User Properties

//The following methods are only available if `SetEmail` was called
// Returns an `OSDeviceState` object with the current immediate device state info
OSDeviceState device = OneSignal.getDeviceState(); 

//Get the OneSignal Email Subscription Id
String emailUserId = device.getEmailUserId();

//Get the email address tied to the device
String emailAddress = device.getEmailAddress();

//This device's email subscription status
boolean isEmailSubscribed = device.isEmailSubscribed();

SMS User Properties

//The following methods are only available if `SetSMSNumber` was called
// Returns an `OSDeviceState` object with the current immediate device state info
OSDeviceState device = OneSignal.getDeviceState(); 

// Get the SMS Phone Number tied to the device. Only available if OneSignal.setSMSNumber() was called.
String smsUserId = device.getSMSUserId();

//Get the phone number tied to the device
String smsNumber = device.getSMSNumber();

//This device's SMS subscription status
boolean isSMSSubscribed = device.isSMSSubscribed();

User Data Change Events

Handling Notification Permission Changes

The onOSPermissionChanged method will be fired on the passed-in object when a notification permission setting changes.

This includes the following events:

  • Notification permission prompt shown (iOS)
  • The user accepting or declining the permission prompt (iOS)
  • Enabling or disabling notifications for your app in the App Settings and after returning to your app

Instance is given to your onOSPermissionChanged method, which provides what the value was (“from”) and what the value is now (“to”).

Any object implementing the OSPermissionObserver and/or the OSSubscriptionObserver protocols can be added as an observer. You can call removePermissionObserver to remove any existing listeners.

OneSignal uses a weak reference to the observer to prevent leaks.

public class MainActivity extends Activity implements OSPermissionObserver {
  protected void onCreate(Bundle savedInstanceState) {
    OneSignal.addPermissionObserver(this);
  }
  
  public void onOSPermissionChanged(OSPermissionStateChanges stateChanges) {
    if (stateChanges.getFrom().getEnabled() &&
        !stateChanges.getTo().getEnabled()) {
         new AlertDialog.Builder(this)
             .setMessage("Notifications Disabled!")
             .show();
      }
   
      Log.i("Debug", "onOSPermissionChanged: " + stateChanges);
  }
}

// Example Logcat entry - User disabling notifications then returning to your app.
// onOSPermissionChanged{"from":{"enabled":true},"to":{"enabled":false}}

Handling Subscription State Changes

The onOSSubscriptionChanged method will be fired on the passed-in object when a notification subscription property changes.

This includes the following events:

  • Getting a push token from Google or Apple
  • Getting a subscription/user id from OneSignal
  • OneSignal.disablePush is called
  • User disables or enables notifications

The instance is given to your onOSSubscriptionChanged method which provides what the value was (“from”) and what the value is now (“to”).

Any object implementing the OSPermissionObserver and/or the OSSubscriptionObserver protocols can be added as an observer. You can call removePermissionObserver to remove any existing listeners.

OneSignal uses a weak reference to the observer to prevent leaks.

public class MainActivity extends Activity implements OSSubscriptionObserver {
  protected void onCreate(Bundle savedInstanceState) {
    OneSignal.addSubscriptionObserver(this);
  }
  
  public void onOSSubscriptionChanged(OSSubscriptionStateChanges stateChanges) {
    if (!stateChanges.getFrom().getSubscribed() &&
        stateChanges.getTo().getSubscribed()) {
         new AlertDialog.Builder(this)
             .setMessage("You've successfully subscribed to push notifications!")
             .show();
        // get subscription ID
        stateChanges.getTo().getUserId();
      }
   
      Log.i("Debug", "onOSSubscriptionChanged: " + stateChanges);
  }
}

/*
Example Logcat entry - User disabling notifications then returning to your app.
onOSSubscriptionChanged:
{"from":{"pushToken":"APA91bG9cmZ262s5gJhr8jvbg1q7aiviEC6lcOCgAQliEzHKO3eOdX5cm7IQqMSWfy8Od7Ol3jSjFfvCfeO2UYUpanJCURJ8RdhgEuV8grYxOCwPNJr5GoqcWTQOaL9u-qE2PQcFlv4K","userSubscriptionSetting":true,"subscribed":false},
 "to":  {"userId":"22712a53-9b5c-4eab-a828-f18f81167fef","pushToken":"APA91bG9cmZ262s5gJhr8jvbg1q7aiviEC6lcOCgAQliEzHKO3eOdX5cm7IQqMSWfy8Od7Ol3jSjFfvCfeO2UYUpanJCURJ8RdhgEuV8grYxOCwPNJr5GoqcWTQOaL9u-qE2PQcFlv4K","userSubscriptionSetting":true,"subscribed":true}}

setLanguage Method

Language is detected and set automatically through the OneSignal SDK based on the device settings. This method allows you to change that language by passing in the 2-character, lowercase language code. See Supported Languages.

//Requires SDK 3.16.0+
OneSignal.setLanguage("es");

Privacy

setRequiresUserPrivacyConsent Method

For GDPR users, your application should call this method before initialization of the SDK.

If you pass in true, your application will need to call provideUserConsent(true) before the OneSignal SDK gets fully initialized. Until this happens, you can continue to call methods (such as sendTags()), but nothing will happen.

OneSignal.setRequiresUserPrivacyConsent(true);

If your application is set to require the user’s privacy consent, you can provide this consent using this method. Until you call provideUserConsent(true), the SDK will not fully initialize, and will not send any data to OneSignal.

public void onUserTappedProvidePrivacyConsent(View v) {
  //will initialize the OneSignal SDK and enable push notifications
  OneSignal.provideUserConsent(true);
}

Location Data

setLocationShared Method

Disable or enable location collection (defaults to enabled if your app has location permission).

Note: This method must be called before OneSignal initWithLaunchOptions on iOS.

OneSignal.setLocationShared(false);

isLocationShared Method

Return a boolean that indicates location shared state (defaults to true if your app has location permission).

boolean locationShared = OneSignal.isLocationShared();

promptLocation Method

Recommended: use OneSignal’s In-App Message Soft-Prompt before displaying the Native Alert. Details: Location Opt-In Prompt.

Prompts the user for location permissions to allow geotagging from the OneSignal dashboard. This lets you send notifications based on the device’s location. See Location-Triggered Notifications for more details.

Make sure you add location permissions in your AndroidManifest.xml and/or info.plist.

// Make sure you add one of the following permissions
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />

On Android, you need to add the location dependency

dependencies {
  ...
  implementation 'com.google.android.gms:play-services-location:YOUR_PLAY_SERVICES_VERSION'
}

Finally, don’t forget to call the prompt location method

OneSignal.promptLocation();

Push Notifications

Push Prompting

iOS requires prompting users for permission to show push notifications that make sound and “pop-up” on the screen. iOS also supports Provisional Push Notifications which are delivered directly to the device’s notification center.

Android 13+ requires prompting users for permission to show push notifications. This is different behavior from previous Android versions. More details in our Android 13 Push Notification Developer Update Guide.

You can display this prompt using the OneSignal SDK in 2 ways:

  1. Recommended: use OneSignal’s In-App Message Soft-Prompt before displaying the Native Alert. Details: Prompting for Push Permissions Guide.
  2. Programmatically Trigger the Native Alert Prompt with the OneSignal SDK promptForPushNotifications method.
OneSignal.promptForPushNotifications(userResponse: { accepted in
  print("User accepted notifications: \(accepted)")
})

Notification Events & Payload

OneSignal Provides methods for handling notifications received and clicked/opened events. Details and discussion on implementation and Notification Payload in SDK Notification Event Handlers.

To send notifications to users, we recommend using the Create notification REST API docs, or Messages Dashboard.

postNotification Method

Recommended for scheduling notifications in the future to the current user.

You can only use include_player_ids as a targeting parameter from your app. Other target options such as tags and included_segments require your OneSignal App REST API key which can only be used from your server.

See the Create notification REST API POST call for a list of all possible options.

ParameterTypeDescription
parametersJSONObject, NSDictionary*, JSONString, CallbackContains notification options, see our Create notification POST call for all options.
try {
  OneSignal.postNotification(new JSONObject("{'contents': {'en':'Test Message'}, 'include_player_ids': ['" + "userId" + "']}"),
     new OneSignal.PostNotificationResponseHandler() {
       @Override
       public void onSuccess(JSONObject response) {
         Log.i("OneSignalExample", "postNotification Success: " + response.toString());
       }

       @Override
       public void onFailure(JSONObject response) {
         Log.e("OneSignalExample", "postNotification Failure: " + response.toString());
       }
     });
} catch (JSONException e) {
  e.printStackTrace();
}

clearOneSignalNotifications Method

Android only. iOS provides a standard way to clear notifications by clearing badge count. There is no specific OneSignal API call for clearing notifications.

OneSignal.clearOneSignalNotifications();

disablePush Method

The user must first subscribe through the native prompt or app settings. It does not officially subscribe or unsubscribe them from the app settings, it unsubscribes them from receiving push from OneSignal. You can only call this method with true to opt out users from receiving notifications through OneSignal. You can pass false later to opt users back into notifications.

// Android SDK version 4.x.x
OneSignal.disablePush(true);

//Android SDK version 3.x.x
OneSignal.setSubscription(false);

EnableVibrate & EnableSound Methods

These methods were designed for Android but stopped working in Android 8+ due to a breaking change. To customize going forward, use Android Notification Categories (Channels).

unsubscribeWhenNotificationsAreDisabled Method

Only available on Android Native SDK. If notifications are disabled for your app, unsubscribe the user from OneSignal.

Use case: if notifications are disabled for your app and you still want background notifications to work, pass in false.

OneSignal.unsubscribeWhenNotificationsAreDisabled(false);

setLaunchURLsInApp Method (iOS)

This method can be used to set if launch URLs should be opened in safari or within the application. Set to true to launch all notifications with a URL in the app instead of the default web browser. Make sure to call setLaunchURLsInApp before the setAppId call.

OneSignal.Default.SetLaunchURLsInApp(true); // before Initialize
Parameter TypeDescription
BoolBoolean indicates if launch URLs should be opened in safari or within the application.

Live Activities

Live Activities are a type of interactive push notification. They were designed by Apple to enable iOS apps to provide real-time updates to their users that are visible from the lock screen and dynamic island.

Live Activity support comes with OneSignal iOS SDK version 3.12.3 or above.

Permission

Live Activities do not need explicit user approval. A developer 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.

Developer Guidelines

As with any iOS development, we recommend Apple’s developer guidelines.

According to Apple’s guidelines, applications should give users the option to opt-in to Live Activities. For example, an app can give a user an option to start a Live Activity through it’s UX, such as as a button or in-app. Live Activities must be started when the application is in the foreground.

Enter a Live Activity

Entering a Live Activity associates an activityId with a live activity temporary push token on OneSignal’s server. The activityId is then used with the OneSignal REST API to update one or multiple Live Activities at one time.

ParameterTypeDescription
activityIdStringA customer defined identifier that gets assisted with the temporary push token on OneSignal’s server. When the customer uses the update endpoint they will send this activityId to specify which push tokens they would like to update. NOTE: activityId cannot contain any / (forward slash) characters.
tokenStringA Live Activity temporary push token.

enterliveActivity usage with context:

// ... your app's code 
let activity = try Activity<OneSignalWidgetAttributes>.request(
  attributes: attributes,
  contentState: contentState,
  pushType: .token)
Task {
    for await data in activity.pushTokenUpdates {
        let myToken = data.map {String(format: "%02x", $0)}.joined()
        // ... required code for entering a live activity
        OneSignal.enterLiveActivity("my_activity_id", withToken: myToken)
    }
}

Exit a Live Activity

Exiting a Live activity deletes the association between a customer defined activityId with a Live Activity temporary push token on OneSignal’s server.

exitliveActivity usage

OneSignal.exitLiveActivity("my_activity_id")

In-App Messages

In-App Messages do not require any code to get started, but if you would like to setup custom triggers to display the In-App Message under certain conditions and track IAM lifecycle events, we have SDK methods for you!

See our In-App Message SDK Methods for details.


Email

OneSignal’s Mobile and Web SDKs provide methods for collecting emails, logging out emails, and tracking email subscription changes.

See the Email SDK Methods guide for more details.

If you have a backend server, we strongly recommend using Identity Verification with your users. Your backend can generate an Email authentication token and send it to your app.


SMS

OneSignal’s Mobile and Web SDKs provide methods for collecting phone numbers, logging out phone numbers, and tracking sms subscription.

See the SMS SDK Methods guide for more details.

If you have a backend server, we strongly recommend using Identity Verification with your users. Your backend can generate an SMS authentication token and send it to your app.