OneSignal Help & Documentation

Welcome to the OneSignal New IA developer hub. You'll find comprehensive guides and documentation to help you start working with OneSignal New IA as quickly as possible, as well as support if you get stuck. Let's jump right in!

Get Started    Discussions

Android Native SDK

OneSignal Android Native API Reference

For Developers

Just starting with Android?

Check out our Android SDK Setup guide.

Initialization

Builder Method

Initialize OneSignal

Method

Builder Method

Automatically Prompt Users for Location

Builder Method

Automatically Prompt User to update Google Play if out of date

Builder Method

If notifications are disabled for your app unsubscribe them from OneSignal.

Builder Method

Enable to prevent other broadcast receivers from receiving OneSignal FCM / GCM payloads.

Method

Change how the notification is displayed when your app is actively being used.

Privacy

Method

Delays initialization of the SDK until the user provides privacy consent

Method

Tells the SDK that the user has provided privacy consent (if required)

Method

Returns a boolean indicating if the SDK is waiting for user privacy consent

Status

Method

Current Permission and Subscription status

Method

Permission status changes

Method

Subscription status changes

Tags

Method

View Tags from a User

Method

Method

Add a Tag to a User

Method

Method

Delete a Tag from a User

Method

Data

Method

Prompt Users for Location

Method

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

Receiving Notifications

Method

Send or schedule a notification to a user

Method

Delete a single app notification

Method

Delete all app notifications

Method

Opt users in or out of receiving notifications

Method + Manifest

Add custom data to a notification, or override notification options

Email

Method

Set user's email

Method

Log user out to dissociate email from device

Method

Observer for subscription changes to email

External User ID's

Method

Allows you to use your own system's user ID's to send push notifications to your users. To tie a user to a given user ID, you can use this method.

Method

Removes whatever was set as the current user's external user ID.

Notification Events

Handler

When a notification is received by a device

Handler

When a user takes an action on a notification

Android Manifest

Disable resuming launcher activity when notification is opened

Objects

Object

Information returned from a notification the user received

Object

Notification the user received

Action the user took on the notification

Contents and settings of the notification the user received

In App

Method

Method

Appearance

Method

Change how the notification is displayed when your app is actively being used.

Method

When user receives notification, vibrate device less

Method

When user receives notification, do not play a sound

Android Manifest

Disable badge counts in your app

Debug

Method

Enable logging to help debug OneSignal implementation

Initialization

init

Builder Method

Initializes OneSignal to register the device for push notifications. Should be called in the onCreate method of your Application class.

OneSignal.startInit(this).init();

startInit

Method

Initializes OneSignal to register the device for push notifications. Should be call in the onCreate of your Application class.

Parameter
Type
Description

context

Context

Your Application context.

Returns

OneSignal.Builder - See below for a list of methods available.

public class YourAppClass extends Application {
   @Override
   public void onCreate() {
      super.onCreate();
      OneSignal.startInit(this).init();
   }
}

autoPromptLocation

Builder Method

Prompts the user for location permissions. This allows for geotagging so you can send notifications to users based on location. See promptLocation for more details.

Parameter
Type
Description

prompt

boolean

false (Default) - do not prompt


true - prompt users for location permissions when your app starts.

OneSignal.startInit(this)
  .autoPromptLocation(true)
  .init();

setNotificationReceivedHandler

Builder Method

Sets a notification received handler that will fire when a notification is received. It will be fired when your app is in focus or in the background.

Parameter
Type
Description

handler

Instance to a class implementing this interference.

OneSignal.startInit(this)   
   .setNotificationReceivedHandler(new ExampleNotificationReceivedHandler())
   .init();

See the NotificationReceivedHandler documentation for an example of the ExampleNotificationReceivedHandler class.

setNotificationOpenedHandler

Builder Method

Sets a notification opened handler. The instance will be called when a notification is tapped on from the notification shade or when closing an Alert notification shown in the app.

Parameter
Type
Description

handler

Instance to a class implementing this interference.

OneSignal.startInit(this)   
   .setNotificationOpenedHandler(new ExampleNotificationOpenedHandler())
   .init();

See the NotificationOpenedHandler documentation for an example of the ExampleNotificationOpenedHandler class.

setInFocusDisplaying

Method

Setting to control how OneSignal notifications will be shown when one is received while your app is in focus.

Notification - native notification display while user has app in focus (can be distracting).
InAppAlert (Default) - native alert dialog display, which can be helpful during development.
None - notification is silent.

OneSignal.setInFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification);

setRequiresUserPrivacyConsent

Method

Lets your app require the user's privacy consent before it will initialize. If you call this method and pass in true, the SDK will delay initialization until your application calls `provideUserConsent(true).

If the SDK is waiting for the user's consent, calling any OneSignal SDK methods will do nothing but print a warning. The user will not be registered for push notifications until this happens.

// the SDK will delay initialization and won't collect data.
OneSignal.setRequiresUserPrivacyConsent(true);

provideUserConsent

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);
}

userProvidedPrivacyConsent

Method

Returns a boolean indicating if the user has provided privacy consent.

disableGmsMissingPrompt

Builder Method

Prompts the user to update/enable Google Play services if it's disabled on the device.

Parameter
Type
Description

prompt

boolean

false (Default) - prompt users

true to never show the out of date prompt.

OneSignal.startInit(this)
  .disableGmsMissingPrompt(true)
  .init();

unsubscribeWhenNotificationsAreDisabled

Builder Method

If notifications are disabled for your app, unsubscribe the user from OneSignal. This will happen when your users go to Settings > Apps and turn off notifications, or if they long press one of your notifications and select "block notifications".
This is false by default.

Parameter
Type
Description

prompt

boolean

false (Default) - don't unsubscribe users

true - unsubscribe users when notifications are disabled

OneSignal.startInit(this)
  .unsubscribeWhenNotificationsAreDisabled(true)
  .init();

filterOtherGCMReceivers

Builder Method

Enable to prevent other broadcast receivers from receiving OneSignal FCM / GCM payloads. Prevent thrown exceptions or double notifications form other libraries / SDKs that implement notifications. Other non-OneSignal payloads will still be passed through so your app can handle FCM / GCM payloads from other back-ends. Note however you can't use multiple Google Project numbers / Sender IDs. They must be the same if you are using multiple providers, otherwise there will be unexpected unsubscribes.

OneSignal.startInit(this)
  .filterOtherGCMReceivers(true)
  .init();

Status methods

The following methods provide details on the permission and subscribed state of the device. Use getPermissionSubscriptionState to get the current immediate state and use addPermissionObserver and / or addSubscriptionObserver to react to changes.

Status Recommendations

getPermissionSubscriptionState - Use to load your UI to the correct state. Such as showing a toggle button to enable notifications.

addSubscriptionObserver - Use to update your server when the user becomes subscribed or unsubscribed and to get the OneSignal player / user id.
Example if you need to store the OneSignal player / user id on your backend you can make a REST API call directly from the observer's callback. The OneSignal observer ONLY fires when there is a change, including NOT firing even if the app has been restarted. This helps ensure your not making unnecessary network calls to your backend on each app restart if nothing changed.

getPermissionSubscriptionState

Method

Get the current notification and permission state. Returns a OSPermissionSubscriptionState type described below.

Method
Type
Description

getPermissionStatus()

Android Notification Permissions state

getSubscriptionStatus()

Google and OneSignal subscription state

OSPermissionSubscriptionState status = OneSignal.getPermissionSubscriptionState();
status.getPermissionStatus().getEnabled();
    
status.getSubscriptionStatus().getSubscribed();
status.getSubscriptionStatus().getUserSubscriptionSetting();
status.getSubscriptionStatus().getUserId();
status.getSubscriptionStatus().getPushToken();

OSPermissionState

Class

The Notification permission status of your app. Contains enabled value to know if the user has turned off notifications for your app.

Method
Type
Description

getEnabled()

boolean

true if notifications are enabled.
Will only be false if the user disables notifications for your app from the system settings

OSSubscriptionState

Class

Provides subscription state details of subscribed to push as well as the OneSignal player / user id and the devices push token.

Method
Type
Description

getSubscribed()

boolean

true if the device can receive push notifications from OneSignal.
false if the device has disabled push notifications or not successfully registered yet with either OneSignal or FCM with a valid push token.

getUserSubscriptionSetting()

boolean

Will be true unless you have called setSubscription with false.

getUserId()

String

The OneSignal player / user id for the device.
null if the device hasn't registered with OneSignal's server yet.

getPushToken()

String

The GCM / FCM push token for the device.
null if the device hasn't registered with Google's server yet.


addPermissionObserver

Handler

The onOSPermissionChanged method will be fired on the passed-in object when a notification permission setting changes. This happens when the user enables or disables notifications for your app from the system settings outside of your app. Disable detection is supported on Android 4.4+.

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

Keep a Reference

Make sure to hold a reference to your observable at the class level, otherwise it my not fire.

Leak Safe

OneSignal holds a weak reference to your observer so it's guaranteed not to leak your Activity.

OSPermissionStateChanges

Class

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

Method
Type
Description

getFrom()

What the state was

getTo()

What the state is now


addSubscriptionObserver

Method

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

This includes the following events:

  • Getting a Registration Id (push token) from Google
  • Getting a player / user id from OneSignal
  • OneSignal.setSubscription is called
  • User disables or enables notifications
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 player ID
        stateChanges.getTo().getUserId();
      }
   
      Log.i("Debug", "onOSPermissionChanged: " + 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}}

Keep a Reference

Make sure to hold a reference to your observable at the class level, otherwise it my not fire.

Leak Safe

OneSignal holds a weak reference to your observer so it's guaranteed not to leak your Activity.

OSSubscriptionStateChanges

Class

Instance is given to your onOSSubscriptionChanged method which provides what the value was ("from") and what the value is now ("to").

Method
Type
Description

getFrom()

What the state was (past)

getTo()

What the state is now


Tags

sendTag

Method

Tag a user based on an app event of your choosing so later you can create segments in Segments to target these users. Use sendTags if you need to set more than one tag on a user at a time.

Parameter
Type
Description

key

String

Key of your choosing to create or update.

value

String

Value to set on the key. NOTE: Passing in a blank String deletes the key, you can also call deleteTag or deleteTags.

OneSignal.sendTag("key", "value");

sendTags

Method

Tag a user based on an app event of your choosing so later you can create segments in Segments to target these users.

Parameter
Type
Description

keyValues

JSONObject

Key value pairs of your choosing to create or update. NOTE: Passing in a blank String as a value deletes the key, you can also call deleteTag or deleteTags.

	JSONObject tags = new JSONObject();
	tags.put("key1", "value1");
	tags.put("key2", "value2");
	OneSignal.sendTags(tags);

getTags

Method

Retrieve a list of tags that have been set on the user from the OneSignal server.

Parameter
Type
Description

handler

GetTagsHandler

Calls tagsAvailable on the Object once the tags are available.

OneSignal.getTags(new GetTagsHandler() {
	@Override
	public void tagsAvailable(JSONObject tags) {
		Log.d("debug", tags.toString());
	}
});

GetTagsHandler

Handler

Interface which you can implement and pass to OneSignal.getTags to get the all the tags set on a user from onesignal.com.

Thread Safety

The tagsAvailable callback does not return on the Main(UI) Thread, so be aware when modifying UI in this method.

deleteTag

Method

Deletes a single tag that was previously set on a user with sendTag or sendTags. Use deleteTags if you need to delete more than one.

Parameter
Type
Description

key

String

Key to remove.

OneSignal.deleteTag("key");

deleteTags

Method

Deletes one or more tags that were previously set on a user with sendTag or sendTags.

Parameter
Type
Description

keys

Collection<String>

Keys to remove.

Collection<String> tempList = new ArrayList<String>();
tempList.add(key);
OneSignal.deleteTags(tempList);

tagsAvailable

Method

Parameter
Type
Description

tags

JSONObject

Contains key-value pairs retrieved from the OneSignal server

OneSignal.getTags(new GetTagsHandler() {
  @Override
	public void tagsAvailable(JSONObject tags) {
		Log.d("debug","Current Tags on User:" + tags.toString());
	}
});

Data

promptLocation

Method

Prompts the user for location permissions. This allows for geotagging so you can send notifications to users based on location.

OneSignal.promptLocation();

Make sure you have one of the following permissions in your AndroidManifest.xml as well.

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

setLocationShared

Method

OneSignal.setLocationShared(false);

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

Sending Notifications

postNotification

Method

Allows you to send notifications from user to user or schedule ones in the future to be delivered to the current device.

Parameter
Type
Description

parameters

JSONObject

Contains notification options, see Create Notification POST call for all options.

postNotificationResponseHandler

Fires delegate when the notification was created or fails to be created.

Response
Method

Success

void onSuccess(JSONObject response)

Failure

void onFailure(JSONObject response)

try {
  OneSignal.postNotification(new JSONObject("{'contents': {'en':'Test Message'}, 'include_player_ids': ['" + userId + "']}"), null);
} catch (JSONException e) {
  e.printStackTrace();
}
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();
}

See the Create Notification REST API POST call for a list of all possible options. Note: 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.

cancelNotification

Method

Cancels a single OneSignal notification based on its Android notification integer id. Use instead of Android's NotificationManager.cancel(id); otherwise the notification will be restored when your app is restarted.

int id = 1234;
OneSignal.cancelNotification(id);

clearOneSignalNotifications

Method

Removes all OneSignal notifications from the Notification Shade. If you just use NotificationManager.cancelAll(); OneSignal notifications will be restored your app is restarted.

OneSignal.clearOneSignalNotifications();

setSubscription

Method

You can call this method with false to opt users out of receiving all notifications through OneSignal. You can pass true later to opt users back into notifications.

Parameter
Type

enable

boolean

OneSignal.setSubscription(false);

NotificationExtenderService

Method

Sending Background Data and Overriding Notification Parameters

See our Android Customization Docs for more on advanced android customizations and features like sending data/silent notifications and adding custom data to notifications.

Email

setEmail

Method

setEmail allows you to set the user's email address with the OneSignal SDK. We offer several overloaded versions of this method.

OneSignal.setEmail("example@domain.com");

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. The following code also includes callbacks:

String email = "example@domain.com";
String emailAuthHash = "..."; // Email auth hash generated from your server
OneSignal.setEmail(email, emailAuthHash, new OneSignal.EmailUpdateHandler() {
  @Override
  public void onSuccess() {
    // Email successfully synced with OneSignal
  }

  @Override
  public void onFailure(OneSignal.EmailUpdateError error) {
    // Error syncing email, check error.getType() and error.getMessage() for details
  }
});

logoutEmail

Method

If your app implements logout functionality, you can call logoutEmail to dissociate the email from the device:

OneSignal.logoutEmail();

addEmailSubscriptionObserver

Method

We have also added a new email subscription observer to track changes to email subscriptions (ie. the user sets their email or logs out). In order to subscribe to email subscription changes you can implement the following:

OneSignal.addEmailSubscriptionObserver(subscriptionObserver);

Now, whenever the email subscription changes, this method will be called:

OSEmailSubscriptionObserver subscriptionObserver = new OSEmailSubscriptionObserver() {
   @Override
   public void onOSEmailSubscriptionChanged(OSEmailSubscriptionStateChanges stateChanges) {
   }
};

External UserID's

setExternalUserId

Method

If your system assigns unique identifiers to users, it can be annoying to have to also remember their OneSignal user ID's as well. To make things easier, OneSignal now allows you to set an external_id for your users. Simply call this method, pass in your custom user ID (as a string), and from now on when you send a push notification, you can use include_external_user_ids instead of include_player_ids.

String myCustomUniqueUserId = "something from my backend server";

OneSignal.setExternalUserId(myCustomUniqueUserId);

removeExternalUserId

Method

If your user logs out of your app and you would like to disassociate their custom user ID from your system with their OneSignal user ID, you will want to call this method.

//usually called after the user logs out of your app
OneSignal.removeExternalUserId();

Receiving Notifications

NotificationReceivedHandler

Handler

Fires when a notification is received. It will be fired when your app is in focus or in the background.

Parameter
Type
Description

notification

Contains both the user's response and properties of the notification.

Important behavior notes

  • If you will be displaying your own in app message when a notification is received make sure to call inFocusDisplaying with None to disable OneSignal's in app AlertBox.
  • If want to change how a notification is displayed in the notification shade or process a silent notification when your app isn't running see our Background Data and Notification Overriding guide.
class ExampleNotificationReceivedHandler implements OneSignal.NotificationReceivedHandler {
  @Override
  public void notificationReceived(OSNotification notification) {
    JSONObject data = notification.payload.additionalData;
    String customKey;

    if (data != null) {
      customKey = data.optString("customkey", null);
      if (customKey != null)
        Log.i("OneSignalExample", "customkey set with value: " + customKey);
    }
  }
}

NotificationOpenedHandler

Handler

Use to process a OneSignal notification the user just tapped on.

Parameter
Type
Description

result

Contains both the user's response and properties of the notification.

class ExampleNotificationOpenedHandler implements OneSignal.NotificationOpenedHandler {
  // This fires when a notification is opened by tapping on it.
  @Override
  public void notificationOpened(OSNotificationOpenResult result) {
    OSNotificationAction.ActionType actionType = result.action.type;
    JSONObject data = result.notification.payload.additionalData;
    String customKey;

    if (data != null) {
      customKey = data.optString("customkey", null);
      if (customKey != null)
        Log.i("OneSignalExample", "customkey set with value: " + customKey);
    }

    if (actionType == OSNotificationAction.ActionType.ActionTaken)
      Log.i("OneSignalExample", "Button pressed with id: " + result.action.actionID);

    // The following can be used to open an Activity of your choice.
    // Replace - getApplicationContext() - with any Android Context.
    // Intent intent = new Intent(getApplicationContext(), YourActivity.class);
    // intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
    // startActivity(intent);

     // Add the following to your AndroidManifest.xml to prevent the launching of your main Activity
     //   if you are calling startActivity above.
     /* 
        <application ...>
          <meta-data android:name="com.onesignal.NotificationOpened.DEFAULT" android:value="DISABLE" />
        </application>
     */
  }
}

OSNotificationOpenResult

Class

The information returned from a notification the user received.

Parameter
Type
Description

notification

Notification the user received.

action

The action the user took on the notification.

OSNotification

Class

The notification the user received.

Parameter
Type
Description

isAppInFocus

boolean

Was app in focus.

shown

boolean

Was notification shown to the user. Will be false for silent notifications.

androidNotificationId

int

Android Notification assigned to the notification. Can be used to cancel or replace the notification.

payload

Payload received from OneSignal.

displayType

How the notification was displayed to the user. Can be set to Notification, InAppAlert, or None if it was not displayed.

groupedNotifications

Notification is a summary notification for a group this will contain all notification payloads it was created from.

DisplayType

How the notification was displayed to the user. Part of OSNotification. See inFocusDisplaying for more information on how this is used.

Notification - native notification display.
InAppAlert (Default) - native alert dialog display.
None - notification is silent, or inFocusDisplaying is disabled.

OSNotificationAction

Class

The action the user took on the notification.

Parameter
Type
Description

type

ActionType

Was the notification opened normally (Opened) or was a button pressed on the notification (ActionTaken).

actionID

String

If type == ActionTaken then this will contain the id of the button pressed.

OSNotificationPayload

Class

Contents and settings of the notification the user received.

Parameter
Type
Description

notificationID

String

OneSignal notification UUID.

title

String

Title of the notification.

body

String

Body of the notification.

additionalData

JSONObject

Custom additional data that was sent with the notification. Set on the dashboard under Options > Additional Data or with the 'data' field on the REST API.

smallIcon

String

Small icon resource name set on the notification.

largeIcon

String

Large icon set on the notification.

bigPicture

String

Big picture image set on the notification.

smallIconAccentColor

String

Accent color shown around small notification icon on Android 5+ devices. ARGB format.

launchUrl

String

URL to open when opening the notification.

sound

String

Sound resource to play when the notification is shown. Read more here

ledColor

String

Devices that have a notification LED will blink in this color. ARGB format.

lockScreenVisibility

int

Privacy setting for how the notification should be shown on the lockscreen of Android 5+ devices.

1 (Default) - Public (fully visible)
0 - Private (Contents are hidden)
-1 - Secret (not shown).

groupKey

String

Notifications with this same key will be grouped together as a single summary notification.

groupMessage

string

Summary text displayed in the summary notification.

actionButtons

List of action buttons on the notification.

fromProjectNumber

String

The Google project number the notification was sent under.

backgroundImageLayout

If a background image was set this object will be available.

rawPayload

String

Raw JSON payload string received from OneSignal.

ActionButton

Object

List of action buttons on the notification. Part of OSNotificationPayload.

Parameter
Type
Description

id

String

Id assigned to the button.

text

String

Text show on the button to the user.

icon

String

Icon shown on the button.

BackgroundImageLayout

Object

If a background image was set, this object will be available. Part of OSNotificationPayload.

Parameter
Type
Description

image

String

Image URL or name used as the background image.

titleTextColor

String

Text color of the title on the notification. ARGB Format.

bodyTextColor

String

Text color of the body on the notification. ARGB Format.

Opened Action

Android Manifest

By default OneSignal will open or resume your launcher Activity when a notification is tapped on. You can disable this behavior by adding the meta-data tag com.onesignal.NotificationOpened.DEFAULT set to DISABLE inside your application tag in your AndroidManifest.xml.

<application ...>
   <meta-data android:name="com.onesignal.NotificationOpened.DEFAULT" android:value="DISABLE" />
</application>

Make sure you are initializing OneSignal with setNotificationOpenedHandler in the onCreate method in your Application class. You will need to call startActivity from this callback.

In-App Messaging

Check out In-App Messaging Quickstart to get an overview before diving into the SDK methods below.

In-App - Triggers

Triggers are something you fire in your app based on events/state changes which may show an In-App Message. Every time you add or remove a trigger with the below methods the SDK will evaluate if an In-App Message should be shown based on the Trigger conditions set on it via OneSignal Dashboard when it was created.

Triggers are reset each time your app is closed so make sure to set them again when starting your app if you need any of them to be persistent.

addTrigger

Method

Add a trigger, may show an In-App Message if its triggers conditions were met.

Parameter
Type
Description

key

String

Key for the trigger

value

Object
(String or Number Recommended)

Value for the trigger.
Object passed in will have toString() called if not a String

OneSignal.addTrigger("level", 5);

addTriggers

Method

Add a map of triggers, may show an In-App Message if its triggers conditions were met.

Parameter
Type
Description

triggers

Map<String, Object>

Allows you to set multiple trigger key/value pairs simultaneously

removeTriggerForKey

Method

Removes a single trigger for the given key, may show an In-App Message if its triggers conditions were met.

Parameter
Type
Description

key

String

Key for trigger to remove

OneSignal.removeTriggerForKey("level");

removeTriggersForKeys

Method

Removes a list of triggers based on a collection of keys, may show an In-App Message if its triggers conditions were met.

Parameter
Type
Description

keys

Collection<String>

Removes a collection of triggers from their keys

getTriggerValueForKey

Method

Gets a trigger value for a provided trigger key.

Parameter
Type
Description

key

String

Returns a single trigger value for the given key,
if it exists, otherwise returns null

Return Type
Description

Object

Value if added with addTrigger or null if never set.

Object triggerValue;
triggerValue = OneSignal.getTriggerValueForKey("level");

In App - Misc

pauseInAppMessages

Method

Allows you to temporarily pause all In App Messages. You may want to do this while the user is watching a video playing a match in your game to make sure they don't get interrupted at a bad time.

Parameter
Type
Description

pause

boolean

To pause set true
To resume set false

In App - Handlers

setInAppMessageClickHandler

Builder Method

Sets a In App Message opened handler. The instance will be called when an In App Message action is tapped on.

Parameter
Type
Description

handler

InAppMessageClickHandler

Instance to a class implementing this interference.

Example

OneSignal.startInit(this)   
   .setInAppMessageClickHandler(new InAppMessageClickHandler())
   .init();

InAppMessageClickHandler

Handler

Use to process an In App Message the user just tapped on.

Parameter
Type
Description

result

OSInAppMessageAction

Details about the In App Message action element (button or image) that was tapped on.

Example

   class ExampleInAppMessageClickHandler implements OneSignal.InAppMessageClickHandler {
      // Example of an action id you could setup on the dashboard when creating the In App Message
      private static final String ACTION_ID_MY_CUSTOM_ID = "MY_CUSTOM_ID";

      @Override
      public void inAppMessageClicked(OSInAppMessageAction result) {
         if (ACTION_ID_MY_CUSTOM_ID.equals(result.clickName)) {
            Log.i("OneSignalExample", "Custom Action took place! Starting YourActivity!");
            Intent intent = new Intent(getApplicationContext(), YourActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
         }
      }
   }

OSInAppMessageAction

Class

Details about the In App Message action element (button or image) that was tapped on.

Field
Type
Description

clickName

String

An optional click name defined for the action element.
null if not set

clickUrl

String

An optional URL that opens when the action takes place.
null if not set.

firstClick

boolean

true if this is the first time the user has pressed
any action on the In App Message.

closesMessage

boolean

Did the action close the In App Message.
true the In App Message will animate off the screen.
false the In App Message will stay on screen until the user dismisses.

Appearance

enableVibrate

Method

By default OneSignal always vibrates the device when a notification is displayed unless the device is in a total silent mode. Passing false means that the device will only vibrate lightly when the device is in it's vibrate only mode.

You can link this action to a UI button to give your user a vibration option for your notifications.

OneSignal.enableVibrate(false);

enableSound

Method

By default OneSignal plays the system's default notification sound when the device's notification system volume is turned on. Passing false means that the device will only vibrate unless the device is set to a total silent mode.

You can link this action to a UI button to give your user a different sound option for your notifications.

OneSignal.enableSound(false);

Disable Badges

Android Manifest

The OneSignal SDK automatically sets the badge count on your app to the number of notifications that are currently in the notification shade. If you want to disable this you can add the following to your AndroidManifest.xml.

<application ...>
   <meta-data android:name="com.onesignal.BadgeCount" android:value="DISABLE" />
</application>

You can remove the badge permissions with the following entries.

<uses-permission android:name="com.sec.android.provider.badge.permission.READ" tools:node="remove" />
<uses-permission android:name="com.sec.android.provider.badge.permission.WRITE" tools:node="remove" />
<uses-permission android:name="com.htc.launcher.permission.READ_SETTINGS" tools:node="remove" />
<uses-permission android:name="com.htc.launcher.permission.UPDATE_SHORTCUT" tools:node="remove" />
<uses-permission android:name="com.sonyericsson.home.permission.BROADCAST_BADGE" tools:node="remove" />
<uses-permission android:name="com.sonymobile.home.permission.PROVIDER_INSERT_BADGE" tools:node="remove" />
<uses-permission android:name="com.anddoes.launcher.permission.UPDATE_COUNT" tools:node="remove" />
<uses-permission android:name="com.majeur.launcher.permission.UPDATE_BADGE" tools:node="remove" />
<uses-permission android:name="com.huawei.android.launcher.permission.CHANGE_BADGE" tools:node="remove"/>
<uses-permission android:name="com.huawei.android.launcher.permission.READ_SETTINGS" tools:node="remove" />
<uses-permission android:name="com.huawei.android.launcher.permission.WRITE_SETTINGS" tools:node="remove" />

Debug

setLogLevel

Method

Enable logging to help debug if you run into an issue setting up OneSignal. The following options are available with increasingly more information; NONE, FATAL, ERROR, WARN, INFO, DEBUG, VERBOSE

Parameters
Type
Description

logLevel

LOG_LEVEL

Sets the logging level to print to the Android LogCat log.

visualLevel

LOG_LEVEL

Sets the logging level to show as alert dialogs.

OneSignal.setLogLevel(OneSignal.LOG_LEVEL.DEBUG, OneSignal.LOG_LEVEL.DEBUG);

Android Native SDK


OneSignal Android Native API Reference

For Developers

Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.