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?

ParameterData TypeDescription
Debugging
setLogLevelMethodEnable logging to help debug OneSignal implementation
Initialization
initWithContextMethodInitializes OneSignal.
You should call from your Application.onCreate().
You must also call OneSignal.setAppId() to finish initialization.
setAppIdMethodCall this to set or change the OneSignal appId required for initialization.
Handling Notifications
setNotificationOpenedHandlerHandlerWhen a user takes an action on a notification
Opened ActionAndroid ManifestDisable resuming launcher activity when notification is opened
setNotificationWillShowInForegroundHandlerHandlerWhen a notification is received while your app is in focus.
NotificationServiceExtensionNotificationServiceExtension- 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
setRequiresUserPrivacyConsentMethodDelays initialization of the SDK until the user provides privacy consent
consentGrantedMethodTells the SDK that the user has provided privacy consent (if required)
User StatusMore Details
getDeviceStateMethodReturns a OSDeviceState type which contains subscription status of the device, including userId, isSubscribed, etc.
addPermissionObserverMethodObserver method for Current Device Record's Permission status changes.
addSubscriptionObserverMethodObserver method for Current Device Record's Subscription status changes.
disablePushMethodDisable OneSignal from sending notifications to current device.
External IDs
setExternalUserIdMethodAllows 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.
removeExternalUserIdMethodRemoves whatever was set as the current user's external user ID.
Tagging
getTagsMethodView Tags from current device record.
sendTagMethodAdd a single Data Tag to current device record.
sendTagsMethodAdd multiple Data Tags to current device record.
deleteTagMethodDelete a Tag from current device record.
deleteTagsMethodDelete multiple Tags from current device record.
Location Data
setLocationSharedMethodDisable or Enable SDK location collection. See Handling Personal Data.
isLocationSharedMethodReturns a boolean that indicates if location is shared
promptLocationMethodPrompt Users for Location Not Recommended

Recommended: Use In-App Message Location Opt-In Prompt.
Sending Notifications
postNotificationMethodSend or schedule a notification to a OneSignal Player ID.
removeNotificationMethodRemove a single notification from the Android notification shade
clearOneSignalNotificationsMethodRemove all OneSignal notifications from the Android notification shade
In-App Messaging
addTriggerMethodAdd a trigger, may show an In-App Message if its triggers conditions were met.
addTriggersMethodAdd a map of triggers, may show an In-App Message if its triggers conditions were met.
removeTriggerForKeyMethodRemoves a list of triggers based on a collection of keys, may show an In-App Message if its triggers conditions were met.
getTriggerValueForKeyMethodGets a trigger value for a provided trigger key.
pauseInAppMessagesMethodAllows you to temporarily pause all In App Messages.
setInAppMessageClickHandlerHandlerSets an In App Message opened block
Email
setEmailMethodSet 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.
logoutEmailMethodLog user out to dissociate email from device
addEmailSubscriptionObserverMethodObserver for subscription changes to email
Objects
OSNotificationOpenResultObjectInformation returned from a notification the user received
OSNotificationObjectNotification the user received
OSNotificationActionObjectAction the user took on the notification
OSNotificationPayloadObjectContents and settings of the notification the user received
OSNotificationReceivedEventObjectContains 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.

ParameterTypeDescription
contextContextYour 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 TypeParameter NameDescription
StringnewAppIdString 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 TypeParameter NameDescription
OSNotificationWillShowInForegroundHandlerwillShowInForegroundHandlercallback fires when notification is about to be displayed while your app is in use.
OneSignal.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.

ParameterTypeDescription
handlerNotificationOpenedHandlerInstance 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.
ParameterType
unsubscribeboolean
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:

TypeMethodDescription
booleanisSubscribed()Get whether the device is subscribed to receive OneSignal push notifications.
booleanareNotificationsEnabled()Get whether notifications are enabled on the device at the Android app level.
This is the same value as Android's areNotificationsEnabled() method.
booleanisPushDisabled()Was push disabled with OneSignal.disablePush()
StringgetUserId()Get the OneSignal user (player) id
StringgetPushToken()Get device's push token.
This can be one of the following depending on the device:
- Google FCM token
- Huawei HMS token
- FireOS token
StringgetEmailUserId()Get the OneSignal user email id.
Only available if OneSignal.setEmail() was called.
StringgetEmailAddress()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.

MethodTypeDescription
areNotificationsEnabled()booleantrue 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.

MethodTypeDescription
isSubscribed()booleantrue 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()booleanWas push disabled with OneSignal.disablePush()
getUserId()StringThe OneSignal player / user id for the device.
null if the device hasn't registered with OneSignal's server yet.
getPushToken()StringThe 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").

MethodTypeDescription
getFrom()OSSubscriptionStateWhat the state was
getTo()OSSubscriptionStateWhat 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").

MethodTypeDescription
getFrom()OSPermissionStateWhat the state was (past)
getTo()OSPermissionStateWhat the state is now

disablePush

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

disabledBOOL

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.

ParameterTypeDescription
parametersJSONObjectContains notification options, see Create Notification POST call for all options.

postNotificationResponseHandler

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

ResponseMethod
Successvoid onSuccess(JSONObject response)
Failurevoid 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.

ParameterTypeDescription
resultOSNotificationOpenResultContains 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.

ParameterTypeDescription
notificationOSNotificationNotification the user received.
actionOSNotificationActionThe 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.

TypeMethodDescription
JSONObjectgetAdditionalDataGets 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.
intgetAndroidNotificationIdGets the unique Android Native API identifier.
StringgetNotificationIdGets the OneSignal notification UUID.
StringgetBodyGets the body text of the notification.
StringgetTitleGets the title text of the notification.
StringgetLaunchURLGets the URL opened when opening the notification.
StringgetLargeIconGets the large icon set on the notification.
StringgetBigPictureGets the big picture image set on the notification.
StringgetSmallIconGets the small icon resource name set on the notification.
StringgetSmallIconAccentColorGets the accent color shown around small notification icon on Android 5+ devices. ARGB format.
BackgroundImageLayoutgetBackgroundImageLayoutIf a background image was set, this object will be available.

The following methods on this object return strings:
- getBodyTextColor()
- getImage()
- getTitleTextColor()
StringgetLedColorGet LED string. Devices that have a notification LED will blink in this color. ARGB format.
StringgetCollapseIdGets the collapse id for the notfication.
List<ActionButton>getActionButtonsThe list of action buttons on the notification.

The following methods on this object return strings:
- getIcon()
- getId()
- getText()
intgetPriorityThe priority of the notification. Values range from -2 to 2 (see Android's NotificationCompat reference for more info.
StringgetFromProjectNumberGets the Google project number the notification was sent under.
List<OSNotification>getGroupedNotificationsGets the notification payloads a summary notification was created from.
StringgetGroupKeyNotifications with this same key will be grouped together as a single summary notification.
StringgetGroupMessageGets the summary text displayed in the summary notification.
intgetLockScreenVisibilityPrivacy 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).
StringgetSoundGets the sound resource played when the notification is shown. Read more here
StringgetTemplateId
StringgetTemplateName
OSMutableNotificationmutableCopyExtends OSNotification.
See OSMutableNotification below for more details.
NotificationCompat.ExtendergetNotificationExtenderUsed with OSMutableNotification
StringgetRawPayloadGets raw JSON payload string received from OneSignal

ActionButton

Object

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

ParameterTypeDescription
idStringId assigned to the button.
textStringText show on the button to the user.
iconStringIcon shown on the button.

BackgroundImageLayout

Object

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

ParameterTypeDescription
imageStringImage URL or name used as the background image.
titleTextColorStringText color of the title on the notification. ARGB Format.
bodyTextColorStringText 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
MethodParam TypeDescription
setAndroidNotificationIdintSets the Android Notification Id. Setting this value to an existing notification replaces it in the notification shade
setExtenderNotificationCompat.ExtenderAllow setup an notification extender to allow modifying any notification property.

OSNotificationAction

The action the user took on the notification.

TypeMethodDescription
StringgetActionId()Notification button identifier
ActionTypegetType()The action type.

Enum:
0) Opened - notification was clicked
1) ActionTaken - button was clicked

OSNotificationReceivedEvent

This class is used by the following.

TypeFieldDescription
voidcomplete()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
OSNotificationgetNotification()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.


What’s Next