Android Native - 4.0.0 API Changes

New Methods

Reference
initWithContext()Required: Initializes OneSignal with an Android Context. Call from your Application.onCreate
setAppId()Required: Set the OneSignal app id.
setNotificationWillShowInForegroundHandler()Set the callback to run just before displaying a notification while the app is in focus.
setInAppMessageClickHandler()Set the callback to run on in-app message click.
setNotificationOpenedHandler()Set the callback to run on notification open.
unsubscribeWhenNotificationsAreDisabled()If notifications are disabled for your app, unsubscribe the user from OneSignal.
getDeviceState()Gets information about the device.
setExternalUserId()onComplete is now onSuccess

Initialization

In version 4, we are bringing the OneSignal appId configuration out of the build.gradle file and into the API via the setAppId method. The init method has been simplified and renamed.

Initialization is now a two step process requiring both init and setAppId to be called. One key thing to note is that you can call setAppId at any point in your app's flow. This allows full initialization to be delayed until say, a user logs in.

3+4+
OneSignal.startInit(this).init();OneSignal.initWithContext(this);
OneSignal.setAppId(appId);

initWithContext Method

Sets the global shared ApplicationContext for OneSignal. This is should be set from the Application.onCreate

Parameter TypeParameter NameDescription
ContextcontextContext used by the Application of the app.

setAppId Method

Sets the app id OneSignal should use in the application.

Parameter TypeParameter NameDescription
StringnewAppIdString app id associated with the OneSignal dashboard app.

Example

public class MainApplication extends Application {
    private static final String ONESIGNAL_APP_ID = "########-####-####-####-############";
  
    @Override
    public void onCreate() {
        super.onCreate();
        
        // Uncomment to enable verbose OneSignal logging to debug issues if needed.
        // OneSignal.setLogLevel(OneSignal.LOG_LEVEL.VERBOSE, OneSignal.LOG_LEVEL.NONE);
        
        OneSignal.initWithContext(this);
        OneSignal.setAppId(ONESIGNAL_APP_ID);
    }
}

Removed Methods

❗️

In version 4, there are several methods you should remove.

Deprecated MethodsReplacement
enableSound()Stopped working in Android 8+ due to a breaking change. To customize going forward, use Notification Categories (Channels).
enableVibrate()Stopped working in Android 8+ due to a breaking change. To customize going forward, use Notification Categories (Channels).
getPermissionSubscriptionState()Use getDeviceState() going forward.
idsAvailable()Use getDeviceState or addSubscriptionObserver going forward.
setInFocusDisplaying()Replaced by setNotificationWillShowInForegroundHandler.
removeNotificationOpenedHandler()Replaced by setNotificationOpenedHandler(null).
removeInAppMessageClickHandler()Replaced by setInAppMessageClickHandler(null).
removeNotificationReceivedHandler()No replacement
setSubscription()Replaced by disablePush()
onNotificationProcessing()Replaced by remoteNotificationReceived()
NotificationExtenderServiceRenamed to NotificationServiceExtension
NotificationExtenderService -> OSRemoteNotificationReceivedHandler
onNotificationProcessing -> remoteNotificationReceived

New Methods

Foreground Notification Control

In version 4, you can now specifically read notification data that will display while the app is in focus as well as change the display type dynamically. This allows developers to have even greater control over the notification experience.

setNotificationWillShowInForegroundHandler Method

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

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

Parameter
OSNotificationWillShowInForegroundHandlerCallback

The callback accepts a parameter notificationJob of type NotificationWillShowInForegroundHandler.

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

OSNotificationReceivedEvent methods:

TypeFieldDescription
voidcomplete()Required:
Method controlling notification completion from the handler. If this is not called at the end of the notificationWillShowInForeground implementation, a runnable will fire after a 25 second timer and complete automatically.

Parameter:
- Display: pass the OSNotification object
- Omit: pass null to omit displaying
OSNotificationgetNotification()Method
The notification the user received.

See OSNotification for more details.

Background Notification Control

remoteNotificationReceived() Method

Parameter
OSRemoteNotificationReceivedHandlerCallback

Create a class that extends OSRemoteNotificationReceivedHandler and implement the remoteNotificationReceived method.

The method remoteNotificationReceived parameters are context of type Context and notificationReceivedEvent of type OSNotificationReceivedEvent.

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
      // To omit displaying a notifiation, pass `null` to complete()
      notificationReceivedEvent.complete(mutableNotification);
   }

}

Add it as meta-data to your AndroidManifest.xml file under the application tag.

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

Finally, remove the old com.onesignal.NotificationExtender if had use it in in the 3.x.x release.

<!-- Remove this Service with the following action if you added in from OneSignal 3.x.x -->
<service
        android:name="YOUR_NAMESPACE_AND_CLASS_NAME_HERE"
        android:permission="android.permission.BIND_JOB_SERVICE"
        android:exported="false">
  <intent-filter>
    <action android:name="com.onesignal.NotificationExtender" />
  </intent-filter>
</service>

Click/Open Handlers

setInAppMessageClickHandler Method

Parameter
OSInAppMessageClickHandlerCallback

This method takes a callback that itself accepts a parameter result of type OSInAppMessageAction.

OneSignal.setInAppMessageClickHandler(
   new OneSignal.OSInAppMessageClickHandler() {
       @Override
       public void inAppMessageClicked(OSInAppMessageAction result) {
         String clickName = result.getClickName();
         String clickUrl = result.getClickUrl();
              
         boolean closesMessage = result.doesCloseMessage();
         boolean firstClick = result.isFirstClick();
});

🚧

OSInAppMessageAction fields:

Make sure to update your implementation of the In-App Click Handler. The following fields have now been converted to be returned via getter methods

TypeV3 FieldDescriptionV4 Getter
StringclickNameAn optional click name entered defined by the app developer when creating the IAM.getClickName()
StringclickUrlAn optional URL that opens when the action takes place.getClickUrl()
booleanclosesMessageWhether tapping on the element closed the In-App Message.doesCloseMessage()
booleanfirstClickWhether this was the first action taken on the in app message.isFirstClick()
List<OSInAppMessageOutcome>outcomesOutcome for action.

Mainly useful for debugging
getOutcomes()
List<OSInAppMessagePrompt>promptsPermission prompts.

Mainly useful for debugging
getPrompts()
OSInAppMessageTagtagsTags for action.

Mainly useful for debugging
getTags()
OSInAppMessageActionUrlTypeurlTargetDetermines where the URL is opened, ie.

Mainly useful for debugging
getUrlTarget()

setNotificationOpenedHandler Method

Parameter
OSNotificationOpenedHandler Callback

This method takes a OSNotificationOpenedHandler callback that itself accepts a parameter result of type OSNotificationOpenedResult.

OneSignal.setNotificationOpenedHandler(
   new OneSignal.OSNotificationOpenedHandler() {
     @Override
     public void notificationOpened(OSNotificationOpenedResult result) {
       String actionId = result.getAction().getActionId();
       String type = result.getAction().getType(); // "ActionTaken" | "Opened"
  
       String title = result.getNotification().getTitle();
     }
});

OSNotificationOpenResult fields:

TypeMethodDescription
OSNotificationActiongetAction()The action the user took on the notification.

String - getActionId()
Enum - getType() ("Opened", "ActionTaken")
OSNotificationgetNotification()The notification the user received.
See OSNotification for the full list of properties.

Other Methods

unsubscribeWhenNotificationsAreDisabled Method

If notifications are disabled for your app, unsubscribe the user from OneSignal.

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

OneSignal.unsubscribeWhenNotificationsAreDisabled(false);

getDeviceState Method

Returns an OSDeviceState object with device info.

🚧

Do not cache OSDeviceState object

This method returns a "snapshot" of the device state for when it was called. Make sure to call getDeviceState again to get the latest state.

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 subscribedToOneSignal = device.isUserSubscribed();

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

Other Additions / Changes

NameDescription
OSNotificationProvides a getters for all notification properties such as title, body, additionalData, etc.
Changes: This class replaces OSNotificationPayload as all properties have been merged into this.
OSNotificationActionThe action the user took on the notification.
disablePush()Use this method to opt users out of receiving all notifications through OneSignal.
Replaces: setSubscription()

OSNotification Class

In version 4, the OSNotification class is composed of all getters. The class combines the original OSNotification with data previously on the OSNotificationPayload class into a single large OSNotification class.

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

Methods
- setAndroidNotificationId(int id)
- setExtender(Extender extender)
ExtendergetNotificationExtender
StringgetRawPayloadGets raw JSON payload string received from OneSignal

OSNotificationAction Class

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

disablePush Method

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

TypeParameter
booleandisable