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
initWithContext
MethodSets the global shared ApplicationContext
for OneSignal. This is should be set from the Application.onCreate
Parameter Type | Parameter Name | Description |
---|---|---|
Context | context | Context used by the Application of the app. |
setAppId
Method
setAppId
MethodSets the app id OneSignal should use in the application.
Parameter Type | Parameter Name | Description |
---|---|---|
String | newAppId | String 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 Methods | Replacement |
---|---|
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() |
NotificationExtenderService | Renamed to NotificationServiceExtensionNotificationExtenderService -> 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
setNotificationWillShowInForegroundHandler
MethodRuns 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 | |
---|---|
OSNotificationWillShowInForegroundHandler | Callback |
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:
Type | Field | Description |
---|---|---|
void | complete() | 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 |
OSNotification | getNotification() | Method The notification the user received. See OSNotification for more details. |
Background Notification Control
remoteNotificationReceived()
Method
remoteNotificationReceived()
MethodParameter | |
---|---|
OSRemoteNotificationReceivedHandler | Callback |
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
setInAppMessageClickHandler
MethodParameter | |
---|---|
OSInAppMessageClickHandler | Callback |
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
Type | V3 Field | Description | V4 Getter |
---|---|---|---|
String | clickName | An optional click name entered defined by the app developer when creating the IAM. | getClickName() |
String | clickUrl | An optional URL that opens when the action takes place. | getClickUrl() |
boolean | closesMessage | Whether tapping on the element closed the In-App Message. | doesCloseMessage() |
boolean | firstClick | Whether this was the first action taken on the in app message. | isFirstClick() |
List<OSInAppMessageOutcome> | outcomes | Outcome for action. Mainly useful for debugging | getOutcomes() |
List<OSInAppMessagePrompt> | prompts | Permission prompts. Mainly useful for debugging | getPrompts() |
OSInAppMessageTag | tags | Tags for action. Mainly useful for debugging | getTags() |
OSInAppMessageActionUrlType | urlTarget | Determines where the URL is opened, ie. Mainly useful for debugging | getUrlTarget() |
setNotificationOpenedHandler
Method
setNotificationOpenedHandler
MethodParameter | |
---|---|
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:
Type | Method | Description |
---|---|---|
OSNotificationAction | getAction() | The action the user took on the notification. String - getActionId() Enum - getType() ("Opened", "ActionTaken") |
OSNotification | getNotification() | The notification the user received. See OSNotification for the full list of properties. |
Other Methods
unsubscribeWhenNotificationsAreDisabled
Method
unsubscribeWhenNotificationsAreDisabled
MethodIf 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
getDeviceState
MethodReturns an OSDeviceState
object with device info.
Do not cache
OSDeviceState
objectThis 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:
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 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. |
Other Additions / Changes
Name | Description |
---|---|
OSNotification | Provides 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. |
OSNotificationAction | The 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
OSNotification
ClassIn 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.
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 Methods - setAndroidNotificationId(int id) - setExtender(Extender extender) |
Extender | getNotificationExtender | |
String | getRawPayload | Gets raw JSON payload string received from OneSignal |
OSNotificationAction
Class
OSNotificationAction
ClassThe action the user took on the notification.
Type | Method | Description |
---|---|---|
String | getActionId() | Notification button identifier |
ActionType | getType() | The action type. Enum: 0) Opened - notification was clicked1) ActionTaken - button was clicked |
disablePush
Method
disablePush
MethodUse this method to opt users out of receiving all notifications through OneSignal.
Type | Parameter |
---|---|
boolean | disable |
Updated over 2 years ago