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

πŸ“˜

Just starting with Android?

Check out our Android SDK Setup guide.

πŸ“˜

Latest API

This page is for the latest 4.0.0 version of the API, released Dec. 9, 2020.

Still using the 3.x.x version?

Parameter

Data Type

Description

Debugging

setLogLevel

Method

Enable logging to help debug OneSignal implementation

Initialization

initWithContext

Method

Initializes OneSignal.
You should call from your Application.onCreate().
You must also call OneSignal.setAppId() to finish initialization.

setAppId

Method

Call this to set or change the OneSignal appId required for initialization.

Handling Notifications

setNotificationOpenedHandler

Handler

When a user takes an action on a notification

Opened Action

Android Manifest

Disable resuming launcher activity when notification is opened

setNotificationWillShowInForegroundHandler

Handler

When a notification is received while your app is in focus.

NotificationServiceExtension

NotificationServiceExtension

  • Allows getting notification received events, even if your app is closed

  • Allows reading and modifying the notification, before it is displayed

  • Allows reading data only pushes

Privacy

setRequiresUserPrivacyConsent

Method

Delays initialization of the SDK until the user provides privacy consent

consentGranted

Method

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

User Status

More Details

getDeviceState

Method

Returns a OSDeviceState type which contains subscription status of the device, including userId, isSubscribed, etc.

addPermissionObserver

Method

Observer method for Current Device Record's Permission status changes.

addSubscriptionObserver

Method

Observer method for Current Device Record's Subscription status changes.

disablePush

Method

Disable OneSignal from sending notifications to current device.

External IDs

setExternalUserId

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.

removeExternalUserId

Method

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

Tagging

getTags

Method

View Tags from current device record.

sendTag

Method

Add a single Data Tag to current device record.

sendTags

Method

Add multiple Data Tags to current device record.

deleteTag

Method

Delete a Tag from current device record.

deleteTags

Method

Delete multiple Tags from current device record.

Location Data

setLocationShared

Method

Disable or Enable SDK location collection. See Handling Personal Data.

promptLocation

Method

Prompt Users for Location Not Recommended

Recommended: Use In-App Message Location Opt-In Prompt.

Sending Notifications

postNotification

Method

Send or schedule a notification to a OneSignal Player ID.

removeNotification

Method

Remove a single notification from the Android notification shade

clearOneSignalNotifications

Method

Remove all OneSignal notifications from the Android notification shade

In-App Messaging

addTrigger

Method

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

addTriggers

Method

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

removeTriggerForKey

Method

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

getTriggerValueForKey

Method

Gets a trigger value for a provided trigger key.

pauseInAppMessages

Method

Allows you to temporarily pause all In App Messages.

setInAppMessageClickHandler

Handler

Sets an In App Message opened block

Email

setEmail

Method

Set user's email. Creates a new user record for the email address. Use sendTag if you want to update a push user record with the email.

logoutEmail

Method

Log user out to dissociate email from device

addEmailSubscriptionObserver

Method

Observer for subscription changes to email

Objects

OSNotificationOpenResult

Object

Information returned from a notification the user received

OSNotification

Object

Notification the user received

OSNotificationAction

Object

Action the user took on the notification

OSNotificationPayload

Object

Contents and settings of the notification the user received

OSNotificationReceivedEvent

Object

Contains a completion handler and an OSNotification Object.

Initialization

initWithContext

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.

public class YourAppClass extends Application {

   private static final String ONESIGNAL_APP_ID = "########-####-####-####-############";

   @Override
   public void onCreate() {
      super.onCreate();
      
      OneSignal.initWithContext(this);
      OneSignal.setAppId(ONESIGNAL_APP_ID);
   }
}

setAppId

Sets the OneSignal appId your app will be register to.

Parameter Type

Parameter Name

Description

String

newAppId

String appId associated with the OneSignal.


Handling Notifications

setNotificationWillShowInForegroundHandler

Runs before displaying a notification while the app is in focus.
Use this handler to decide if the notification should show or not.

This runs after the Notification Service Extension which can be used to modify the notification before showing it.

Parameter Type

Parameter Name

Description

OSNotificationWillShowInForegroundHandler

willShowInForegroundHandler

callback fires when notification is about to be displayed while your app is in use.

OneSiganl.setNotificationWillShowInForegroundHandler(new NotificationWillShowInForegroundHandler() {
  @Override
  void notificationWillShowInForeground(OSNotificationReceivedEvent notificationReceivedEvent) {    
    // Get custom additional data you sent with the notification
    JSONObject data = notificationReceivedEvent.notification.getAdditionalData();

    if (/* some condition */ ) {
      // Complete with a notification means it will show
     notificationReceivedEvent.complete(notification);
    }
    else {
      // Complete with null means don't show a notification.
     notificationReceivedEvent.complete(null);
    }
  }
});

setNotificationOpenedHandler

Sets a notification opened handler. The instance will be called when a notification is tapped on from the notification shade.

Parameter

Type

Description

handler

NotificationOpenedHandler

Instance to a class implementing this interference.

OneSignal.setNotificationOpenHandler(new ExampleNotificationOpenedHandler());

NotificationServiceExtension

This OneSignal NotificationServiceExtension allows the following use cases.

  • Allows getting notification received events, even if your app is closed
  • Allows reading and modifying the notification, before it is displayed
  • Allows reading data only pushes

Step 1

Create a class that implements the OSRemoteNotificationReceivedHandler and add the required remoteNotificationReceived method.

import com.onesignal.OSNotification;
import com.onesignal.OSMutableNotification;
import com.onesignal.OSNotificationReceivedEvent;
import com.onesignal.OneSignal.OSRemoteNotificationReceivedHandler;

public class NotificationServiceExtension implements OSRemoteNotificationReceivedHandler {

   @Override
   public void remoteNotificationReceived(Context context, OSNotificationReceivedEvent notificationReceivedEvent) {
      OSNotification notification = notificationReceivedEvent.getNotification();

      // Example of modifying the notification's accent color
      OSMutableNotification mutableNotification = notification.mutableCopy();
      mutableNotification.setExtender(builder -> builder.setColor(context.getResources().getColor(R.color.colorPrimary)));

      // If complete isn't call within a time period of 25 seconds, OneSignal internal logic will show the original notification
      // If null is passed to complete 
      notificationReceivedEvent.complete(mutableNotification);
   }

}

Step 2

Add it as <meta-data ...> in your AndroidManifest.xml under the <application> tag.

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

unsubscribeWhenNotificationsAreDisabled

Android Devices can still get Data/Silent Notifications even if the user disables your app's notifications. 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 true by default, so device will become unsubscribed if the user disables all notifications for your app in the Android settings.
  • Setting this method to false will keep them subscribed for data only push if the user does disable notifications for your app.

Parameter

Type

unsubscribe

boolean

OneSignal.unsubscribeWhenNotificationsAreDisabled(false)

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

getDeviceState - 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.

getDeviceState

Method

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

OSDeviceState device = OneSignal.getDeviceState();

String email = device.getEmailAddress();
String emailId = device.getEmailUserId();
String pushToken = device.getPushToken();
String userId = device.getUserId();

boolean enabled = device.areNotificationsEnabled();
boolean subscribed = device.isSubscribed();
boolean pushDisabled = device.isPushDisabled();

OSDeviceState getters:

Type

Method

Description

boolean

isSubscribed()

Get whether the device is subscribed to receive OneSignal push notifications.

boolean

areNotificationsEnabled()

Get whether notifications are enabled on the device at the Android app level.
This is the same value as Android's areNotificationsEnabled() method.

boolean

isPushDisabled()

Was push disabled with OneSignal.disablePush()

String

getUserId()

Get the OneSignal user (player) id

String

getPushToken()

Get device's push token.
This can be one of the following depending on the device:

  • Google FCM token
  • Huawei HMS token
  • FireOS token

String

getEmailUserId()

Get the OneSignal user email id.
Only available if OneSignal.setEmail() was called.

String

getEmailAddress()

Get the user email address.
Only available if OneSignal.setEmail() was called.

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

areNotificationsEnabled()

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

isSubscribed()

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, HMS, or ADM with a valid push token.

isPushDisabled()

boolean

Was push disabled with OneSignal.disablePush()

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().areNotificationsEnabled() &&
        !stateChanges.getTo().areNotificationsEnabled()) {
         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()

OSSubscriptionState

What the state was

getTo()

OSSubscriptionState

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.disablePush 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().isSubscribed() &&
        stateChanges.getTo().isSubscribed()) {
         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()

OSPermissionState

What the state was (past)

getTo()

OSPermissionState

What the state is now

disablePush

Use this method to opt users out of receiving all notifications through OneSignal.

disabled

BOOL


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.

removeNotification

Method

Removes 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.removeNotification(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();

NotificationOpenedHandler

Handler

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

Parameter

Type

Description

result

OSNotificationOpenResult

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) {
    // Printing out the full OSNotification object to the logcat for easier debugging.
    Log.i("OSNotification", "result.notification.toJSONObject(): " + result.notification.toJSONObject());

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

    OSNotificationAction.ActionType actionType = result.action.type;
    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>
     */
  }
}
// result.notification.toJSONObject().toString(): 
{ 
   "notificationID":"1fe89041-c33b-4bd6-87ad-fdf51157664a",
   "title":"Notification Title",
   "body":"Message of the notification",
   "additionalData":{ 
      "additional_data_key_1":"data_value_1",
      "data_key_2":"data_value_2"
   },
   "smallIcon":"small_icon_resource_name",
   "largeIcon":"https:\/\/img.onesignal.com\/n\/267522bc-e992-48d9-ad13-17d8f3336ae5.png",
   "bigPicture":"https:\/\/img.onesignal.com\/n\/65c5cba1-1bbd-49c4-9b26-ed7036a081f4.jpg",
   "smallIconAccentColor":"FF900FF",
   "launchURL":"https:\/\/onesignal.com\/launch-url",
   "lockScreenVisibility":1,
   "groupKey":"Group_key_23",
   "groupMessage":"Group_message",
   "actionButtons":[ 
      { 
         "id":"action_id",
         "text":"Shown_Text",
         "icon":"Icon_url"
      },
      { 
         "id":"action_id_2",
         "text":"Shown_text_2",
         "icon":"icon_url_2"
      }
   ],
   "fromProjectNumber":"388536902528",
   "collapseId":"collapse_id_1",
   "priority":6,
   "rawPayload":"{\"google.delivered_priority\":\"high\",\"google.sent_time\":1568060314614,\"google.ttl\":280000,\"google.original_priority\":\"high\",\"custom\":\"{\\\"a\\\":{\\\"additional_data_key_1\\\":\\\"data_value_1\\\",\\\"data_key_2\\\":\\\"data_value_2\\\",\\\"actionButtons\\\":[{\\\"id\\\":\\\"action_id\\\",\\\"text\\\":\\\"Shown_Text\\\",\\\"icon\\\":\\\"Icon_url\\\"},{\\\"id\\\":\\\"action_id_2\\\",\\\"text\\\":\\\"Shown_text_2\\\",\\\"icon\\\":\\\"icon_url_2\\\"}],\\\"actionSelected\\\":\\\"__DEFAULT__\\\"},\\\"u\\\":\\\"https:\\\\\\\/\\\\\\\/onesignal.com\\\\\\\/launch-url\\\",\\\"i\\\":\\\"1fe89041-c33b-4bd6-87ad-fdf51157664a\\\"}\",\"oth_chnl\":\"\",\"bgn\":\"1\",\"grp\":\"Group_key_23\",\"pri\":\"6\",\"vis\":\"1\",\"bgac\":\"FF900FF\",\"chnl\":\"{\\\"dscr\\\":\\\"test\\\",\\\"grp_nm\\\":\\\"test\\\",\\\"grp_id\\\":\\\"OS_1249f7c6-cb84-4685-8ba3-1a99b690ccdb\\\",\\\"id\\\":\\\"OS_fb1d04a7-dc4d-4d77-8b0a-8fb48ea2460b\\\",\\\"nm\\\":\\\"High Importance, default sound and vibration\\\"}\",\"from\":\"388536902528\",\"alert\":\"Message of the notification\",\"bicon\":\"https:\\\/\\\/img.onesignal.com\\\/n\\\/65c5cba1-1bbd-49c4-9b26-ed7036a081f4.jpg\",\"licon\":\"https:\\\/\\\/img.onesignal.com\\\/n\\\/267522bc-e992-48d9-ad13-17d8f3336ae5.png\",\"sicon\":\"small_icon_resource_name\",\"title\":\"Notification Title\",\"grp_msg\":\"Group_message\",\"google.message_id\":\"0:1568060314683605%616610dd87cd175f\",\"collapse_key\":\"collapse_id_1\",\"notificationId\":2143835591}"
}

OSNotificationOpenResult

Class

The information returned from a notification the user received.

Parameter

Type

Description

notification

OSNotification

Notification the user received.

action

OSNotificationAction

The action the user took on the notification.

OSNotification

All properties associated with the notification, from message title and body to any custom additional data you may have sent with the notification.

Type

Method

Description

JSONObject

getAdditionalData

Gets 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.

int

getAndroidNotificationId

Gets the unique Android Native API identifier.

String

getNotificationId

Gets the OneSignal notification UUID.

String

getBody

Gets the body text of the notification.

String

getTitle

Gets the title text of the notification.

String

getLaunchURL

Gets the URL opened when opening the notification.

String

getLargeIcon

Gets the large icon set on the notification.

String

getBigPicture

Gets the big picture image set on the notification.

String

getSmallIcon

Gets the small icon resource name set on the notification.

String

getSmallIconAccentColor

Gets the accent color shown around small notification icon on Android 5+ devices. ARGB format.

BackgroundImageLayout

getBackgroundImageLayout

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

The following methods on this object return strings:

  • getBodyTextColor()
  • getImage()
  • getTitleTextColor()

String

getLedColor

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

String

getCollapseId

Gets the collapse id for the notfication.

List<ActionButton>

getActionButtons

The list of action buttons on the notification.

The following methods on this object return strings:

  • getIcon()
  • getId()
  • getText()

int

getPriority

The priority of the notification. Values range from -2 to 2 (see Android's NotificationCompat reference for more info.

String

getFromProjectNumber

Gets the Google project number the notification was sent under.

List<OSNotification>

getGroupedNotifications

Gets the notification payloads a summary notification was created from.

String

getGroupKey

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

String

getGroupMessage

Gets the summary text displayed in the summary notification.

int

getLockScreenVisibility

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).

String

getSound

Gets the sound resource played when the notification is shown. Read more here

String

getTemplateId

String

getTemplateName

OSMutableNotification

mutableCopy

Extends OSNotification.
See OSMutableNotification below for more details.

NotificationCompat.Extender

getNotificationExtender

Used with OSMutableNotification

String

getRawPayload

Gets raw JSON payload string received from OneSignal

ActionButton

Object

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

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 OSNotification.

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.

OSMutableNotification

Can be passed to the OSNotificationReceivedEvent.complete method after modifying notification from the remoteNotificationReceived event.

  • Modifications are currently ignored when used with the notificationWillShowInForeground event

Method

Param Type

Description

setAndroidNotificationId

int

Sets the Android Notification Id. Setting this value to an existing notification replaces it in the notification shade

setExtender

NotificationCompat.Extender

Allow setup an notification extender to allow modifying any notification property.

OSNotificationAction

The action the user took on the notification.

Type

Method

Description

String

getActionId()

Notification button identifier

ActionType

getType()

The action type.

Enum:

  1. Opened - notification was clicked
  2. ActionTaken - button was clicked

OSNotificationReceivedEvent

This class is used by the following.

Type

Field

Description

void

complete()

Required:
Method controlling notification completion from the handler. Must be called within 25 seconds or the original notification will be displayed.

Parameter:

  • Display: pass the OSNotification object
  • Omit: pass null to omit displaying

OSNotification

getNotification()

Method
The notification the user received.

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.

Updated 2 months ago



Android Native SDK


OneSignal Android Native API Reference

Suggested Edits are limited on API Reference Pages

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