Deprecated OneSignal-Android-SDK 3.x.x version
This is for the older 3.x.x version of the API. Please see the latest API reference here
Just starting with Android?
Check out our Android SDK Setup guide.
Parameter | Data Type | Description |
---|---|---|
Debugging | ||
Method | Enable logging to help debug OneSignal implementation | |
Initialization | ||
| Builder Method | Initializes OneSignal to register the device for push notifications. Should be called in the |
Method | ||
Method | Setting to control how OneSignal notifications will be shown when one is received while your app is in focus. | |
Builder 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. | |
Handling Notifications | ||
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 | |
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) | |
User Status | ||
Method | Get the current notification and permission state. Returns a | |
Method | Observer method for Current Device Record's Permission status changes. | |
Method | Observer method for Current Device Record's Subscription status changes. | |
Method | Disable OneSignal from sending notifications to current device. | |
External IDs | ||
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. | |
Tagging | ||
Method | View Tags from current device record. | |
Method | Add a single Data Tag to current device record. | |
Method | Add multiple Data Tags to current device record. | |
Method | Delete a Tag from current device record. | |
Method | Delete multiple Tags from current device record. | |
Location Data | ||
Method | Disable or Enable SDK location collection. See Handling Personal Data. | |
Method | Prompt Users for Location Not Recommended Recommended: Use In-App Message Location Opt-In Prompt. | |
Sending Notifications | ||
Method | Send or schedule a notification to a OneSignal Player ID. | |
Method | Delete a single app notification | |
Method | Delete all app notifications | |
In-App Messaging | ||
Method | Add a trigger, may show an In-App Message if its triggers conditions were met. | |
Method | Add a map of triggers, may show an In-App Message if its triggers conditions were met. | |
Method | Removes a list of triggers based on a collection of keys, may show an In-App Message if its triggers conditions were met. | |
Method | Gets a trigger value for a provided trigger key. | |
Method | Allows you to temporarily pause all In App Messages. | |
Handler | Sets an In App Message opened block | |
Method | Set user's email. Creates a new user record for the email address. Use | |
Method | Log user out to dissociate email from device | |
Method | Observer for subscription changes to email | |
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 | ||
Appearance | ||
Method | When user receives notification, vibrate device less | |
Method | When user receives notification, do not play a sound |
Initialization
startInit
startInit
Initializes OneSignal to register the device for push notifications. Should be call in the onCreate
of your Application class.
Parameter | Type | Description |
---|---|---|
| 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
autoPromptLocation
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 |
---|---|---|
| boolean | `false` (Default) - do not prompt `true` - prompt users for location permissions when your app starts. |
OneSignal.startInit(this)
.autoPromptLocation(true)
.init();
setNotificationReceivedHandler
setNotificationReceivedHandler
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 |
---|---|---|
| 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
setNotificationOpenedHandler
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 |
---|---|---|
| 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.
disableGmsMissingPrompt
disableGmsMissingPrompt
Prompts the user to update/enable Google Play services if it's disabled on the device.
Parameter | Type | Description |
---|---|---|
| boolean | `false` (Default) - prompt users `true` to never show the out of date prompt. |
OneSignal.startInit(this)
.disableGmsMissingPrompt(true)
.init();
unsubscribeWhenNotificationsAreDisabled
unsubscribeWhenNotificationsAreDisabled
Android Devices can still get Data/Silent Notifications even if the user unsubscribes from the App Settings. 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".
If notifications are disabled for your app, setting this method to true
will unsubscribe the user from OneSignal and re-subscribe them if they turn notifications back on.
This is false
by default, so Android users will be marked as subscribed in this case and can receive data/silent notifications. They will not see any data or get alerted if they unsubscribed from the App Settings.
Parameter | Type | Description |
---|---|---|
| boolean | `false` (Default) - don't unsubscribe users `true` - unsubscribe users when notifications are disabled |
OneSignal.startInit(this)
.unsubscribeWhenNotificationsAreDisabled(true)
.init();
filterOtherGCMReceivers
filterOtherGCMReceivers
Prevents other broadcast receivers from receiving OneSignal FCM/GCM payloads i.e. stops other libraries that implement notifications from throwing exceptions or showing double notifications when a OneSignal Notification is received.
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
getPermissionSubscriptionState
Get the current notification and permission state. Returns a OSPermissionSubscriptionState
type described below.
Method | Type | Description |
---|---|---|
| Android Notification Permissions state | |
| 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
OSPermissionState
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 |
---|---|---|
|
|
|
OSSubscriptionState
OSSubscriptionState
Provides subscription state details of subscribed to push as well as the OneSignal player / user id and the devices push token.
Method | Type | Description |
---|---|---|
|
|
|
|
| Will be |
|
| The OneSignal player / user id for the device. |
|
| The GCM / FCM push token for the device. |
addPermissionObserver
addPermissionObserver
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
OSPermissionStateChanges
Instance is given to your onOSPermissionChanged
method which provides what the value was ("from") and what the value is now ("to").
Method | Type | Description |
---|---|---|
| What the state was | |
| What the state is now |
addSubscriptionObserver
addSubscriptionObserver
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
OSSubscriptionStateChanges
Instance is given to your onOSSubscriptionChanged
method which provides what the value was ("from") and what the value is now ("to").
Method | Type | Description |
---|---|---|
| What the state was (past) | |
| What the state is now |
Sending Notifications
postNotification
postNotification
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 |
---|---|---|
| JSONObject | Contains notification options, see Create Notification POST call for all options. |
postNotificationResponseHandler
postNotificationResponseHandler
Fires delegate when the notification was created or fails to be created.
Response | Method |
---|---|
Success |
|
Failure |
|
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
cancelNotification
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
clearOneSignalNotifications
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();
Receiving Notifications
NotificationReceivedHandler
NotificationReceivedHandler
Fires when a notification is received. It will be fired when your app is in focus or in the background.
Parameter | Type | Description |
---|---|---|
| Contains both the user's response and properties of the notification. |
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
NotificationOpenedHandler
Use to process a OneSignal notification the user just tapped on.
Parameter | Type | Description |
---|---|---|
| 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;
Log.i("OSNotificationPayload", "result.notification.payload.toJSONObject().toString(): " + result.notification.payload.toJSONObject().toString());
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>
*/
}
}
//result.notification.payload.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
OSNotificationOpenResult
The information returned from a notification the user received.
Parameter | Type | Description |
---|---|---|
| Notification the user received. | |
| The action the user took on the notification. |
OSNotification
OSNotification
The notification the user received.
Parameter | Type | Description |
---|---|---|
| boolean | Was app in focus. |
| boolean | Was notification shown to the user. Will be false for silent notifications. |
| int | Android Notification assigned to the notification. Can be used to cancel or replace the notification. |
| Payload received from OneSignal. | |
| How the notification was displayed to the user. Can be set to | |
| List<OSNotificationPayload> | Notification is a summary notification for a group this will contain all notification payloads it was created from. |
DisplayType
DisplayType
How the notification was displayed to the user. Part of OSNotification. See [inFocusDisplaying](https://documentation.onesignal.com/docs/sdk-reference#app-in-focus-notification-display for more information on how this is used.
Notification
- native notification display.
InAppAlert
(Default) - native alert dialog display (note this is not an In-App Message).
None
- notification is silent, or inFocusDisplaying is disabled.
OSNotificationAction
OSNotificationAction
The action the user took on the notification.
Parameter | Type | Description |
---|---|---|
| ActionType | Was the notification opened normally ( |
| String | If |
OSNotificationPayload
OSNotificationPayload
Contents and settings of the notification the user received.
Parameter | Type | Description |
---|---|---|
| String | OneSignal notification UUID. |
| String | Title of the notification. |
| String | Body of the notification. |
| 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. |
| String | Small icon resource name set on the notification. |
| String | Large icon set on the notification. |
| String | Big picture image set on the notification. |
| String | Accent color shown around small notification icon on Android 5+ devices. ARGB format. |
| String | URL to open when opening the notification. |
| String | Sound resource to play when the notification is shown. Read more here |
| String | Devices that have a notification LED will blink in this color. ARGB format. |
| int | Privacy setting for how the notification should be shown on the lockscreen of Android 5+ devices.
|
| String | Notifications with this same key will be grouped together as a single summary notification. |
| string | Summary text displayed in the summary notification. |
| List<ActionButton> | List of action buttons on the notification. |
| String | The Google project number the notification was sent under. |
| If a background image was set this object will be available. | |
| String | Raw JSON payload string received from OneSignal. |
ActionButton
ActionButton
List of action buttons on the notification. Part of OSNotificationPayload.
Parameter | Type | Description |
---|---|---|
| String | Id assigned to the button. |
| String | Text show on the button to the user. |
| String | Icon shown on the button. |
BackgroundImageLayout
BackgroundImageLayout
If a background image was set, this object will be available. Part of OSNotificationPayload.
Parameter | Type | Description |
---|---|---|
| String | Image URL or name used as the background image. |
| String | Text color of the title on the notification. ARGB Format. |
| String | Text color of the body on the notification. ARGB Format. |
Opened Action
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.
Appearance
enableVibrate
enableVibrate
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
enableSound
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);
Updated about a month ago