Android SDK Reference
Android SDK Java Reference
Configuration options | |
Client ID | The client ID found in your WonderPush dashboard. |
Client secret | The client secret found in your WonderPush dashboard. |
Sender ID | The sender ID found in your Firebase Cloud Messaging settings. |
Auto init | Allows deactivation of the automatic initialization of the SDK |
Logging | Controls debug logging. |
Requires user consent | Controls whether user consent is required for the SDK to operate. |
Geolocation | Controls whether geolocation is collected or not. |
Subscribing users | |
subscribeToNotifications | Prompts user to subscribe to push notifications. |
unsubscribeFromNotifications | Unsubscribes user from push notifications. |
isSubscribedToNotifications | Tells whether user is subscribed to push notifications. |
Segmentation | |
trackEvent | Sends an event with a name and payload of your choice. |
addTag | Adds one or more tags to this installation. |
removeTag | Removes one or more tags from this installation. |
removeAllTags | Removes all tags from this installation. |
hasTag | Tests whether a given tag is attached to this installation. |
getTags | Returns all the tags attached of this installation. |
getPropertyValue | Returns the value of a given property associated to this installation. |
getPropertyValues | Returns an immutable list of the values of a given property associated to this installation. |
addProperty | Adds the value to a given property associated to this installation. |
removeProperty | Removes the value from a given property associated to this installation. |
setProperty | Sets the value to a given property associated to this installation. |
unsetProperty | Removes the value of a given property associated to this installation. |
putProperties | Associates the provided name/value pairs to this installation. |
getProperties | Returns all the name/value pairs associated to this installation using putProperties. |
getCountry | Returns the user's country. |
setCountry | Overrides the user's country. |
getCurrency | Returns the user's currency. |
setCurrency | Overrides the user's currency. |
getLocale | Returns the user's locale. |
setLocale | Overrides the user's locale. |
getTimeZone | Returns the user's time zone. |
setTimeZone | Overrides the user's time zone. |
User IDs | |
setUserId | Assigns your own user ID to an installation. |
getUserId | Returns the user ID you've assigned to this installation if any. |
Installation info | |
getInstallationId | Returns the installationId identifying this installation in your application. |
getPushToken | Returns the push token (also called registration id by FCM). |
Privacy | |
getUserConsent | Queries privacy consent. |
setUserConsent | Provides privacy consent. |
disableGeolocation | Disables collection of the geolocation. |
enableGeolocation | Enables collection of the geolocation. |
setGeolocation | Overrides the user's current geolocation. |
clearEventsHistory | Clears all events recorded using trackEvent. |
clearPreferences | Clears all the name/value pairs associated to this installation using putProperties. |
clearAllData | Deletes any event, installation and potential user objects associated with all installations present on the device. |
downloadAllData | Initiates the download of all the WonderPush data related to the current installation, in JSON format. |
Delegate interface | |
setDelegate | Sets the delegate for the WonderPushSDK. |
urlForDeepLink | Lets you overwrite URLs that WonderPush will open when launching an Intent to open a deep-link. |
Broadcast intents | |
Broadcast notification clicked | A broadcast intent fired when users click a broadcast push notification. |
Popup (formerly known as in-app messaging | |
setMessageDisplayComponent | Lets you handle the display of popups yourself. |
setMessagesSuppressed | Calling this method with true prevents the display of any popup. Calling with false permits the display of popups again. By default, the display of popups is permitted. |
addImpressionListener | Lets you specify a InAppMessagingImpressionListener called whenever an popups is displayed. |
addClickListener | Lets you specify a InAppMessagingClickListener called whenever an popups is clicked. |
addDisplayErrorListener | Lets you specify a InAppMessagingDisplayErrorListener called whenever a display error occurs. |
Configuration options
Configuring the WonderPush Android SDK is done from your app's app/build.gradle
file.
Configuration options are specified using the buildConfigField
gradle method.
apply plugin: 'com.android.application'
android {
compileSdkVersion 27
defaultConfig {
buildConfigField 'String', 'WONDERPUSH_CLIENT_ID', '"YOUR_WONDERPUSH_CLIENT_ID"'
buildConfigField 'String', 'WONDERPUSH_CLIENT_SECRET', '"YOUR_WONDERPUSH_CLIENT_SECRET"'
buildConfigField 'String', 'WONDERPUSH_SENDER_ID', '"YOUR_FIREBASE_SENDER_ID"'
}
}
Syntax
The buildConfigField
gradle method accepts 3 arguments:
- the Java value type (i.e.
String
orboolean
), - the field name,
- the java field value as you'd write it in a source code file, including double quotes for strings.
// Here's a String example, note the double quotes (") on the 3rd argument.
buildConfigField 'String', 'SOME_STRING_SETTING', '"SOME VALUE"'
// Here's a boolean example.
buildConfigField 'boolean', 'SOME_BOOL_SETTING', 'true'
Customizing values for a given build type
You can specify buildConfigField
directives in the buildTypes
section of your gradle file to make those settings apply only to a given build type.
Here's an example where we specify differents WONDERPUSH_CLIENT_ID
and WONDERPUSH_CLIENT_SECRET
settings for development and production:
android {
buildTypes {
debug {
buildConfigField 'String', 'WONDERPUSH_CLIENT_ID', '"DEBUG_WONDERPUSH_CLIENT_ID"'
buildConfigField 'String', 'WONDERPUSH_CLIENT_SECRET', '"DEBUG_WONDERPUSH_CLIENT_SECRET"'
}
release {
buildConfigField 'String', 'WONDERPUSH_CLIENT_ID', '"RELEASE_WONDERPUSH_CLIENT_ID"'
buildConfigField 'String', 'WONDERPUSH_CLIENT_SECRET', '"RELEASE_WONDERPUSH_CLIENT_SECRET"'
}
}
}
Alternate ways of specifying configuration options
Using the buildConfigField
gradle function is the preferred way of specifying configuration options.
There are 2 alternate ways of specifying configuration options:
- using
string
resources, you can vary configuration options by build flavor, - using Manifest
meta-data
in yourAndroidManifest.xml
's<application>
section.
Here are examples of specifying the WONDERPUSH_CLIENT_ID
in string resources and Manifest meta data:
<string name="wonderpush_clientId" translatable="false">YOUR_CLIENT_ID</string>
<application>
<meta-data android:name="com.wonderpush.sdk.clientId" android:value="YOUR_CLIENT_ID" />
</application>
Specifying where to find the BuildConfig class
If the SDK initializes properly and you see no message in the logs, then you don't need to look at this section.
If you do not use applicationIdSuffix
or applicationId
inside productFlavors
in your build.gradle
, or if your Application
class is in the default location, the SDK will find its configuration. Otherwise, read on.
The WonderPush Android SDK since v3.1.1 puts some effort into finding the location of the BuildConfig
class in order to find the configured buildConfigField
s, but unfortunately there is no silver bullet as this information is erased at build time.
You can give the WonderPush SDK the package where to search for the BuildConfig
class using a string resource or a manifest meta-data. The value you need to provide is the one you see in the package
attribute of the top <manifest>
tag of your AndroidManifest.xml
.
For example, you must give the value com.mycompany.myapp
if your manifest reads the following:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mycompany.myapp">
Here is how to give that value to the SDK:
<!-- Put this inside the <application> tag -->
<meta-data android:name="com.wonderpush.sdk.buildConfigPackage"
android:value="com.mycompany.myapp" />
android {
defaultConfig {
// The easiest way is to hard-code the right value
resValue "string", "wonderpush_buildConfigPackage", "com.mycompany.myapp"
// If your setup is not too twisted, this will work too
resValue "string", "wonderpush_buildConfigPackage", "${defaultConfig.applicationId}"
// If your project layout is standard, this will read the value directly from the AndroidManifest.xml file
resValue "string", "wonderpush_buildConfigPackage", "${new XmlSlurper().parse(file("src/main/AndroidManifest.xml"))[email protected]()}"
}
}
<string name="wonderpush_buildConfigPackage" translatable="false">com.mycompany.myapp</string>
Go ahead and confirm that the SDK is properly initialized, looking out for logs.
Client ID
The client id is used to identify the WonderPush project to work on.
buildConfigField 'String', 'WONDERPUSH_CLIENT_ID', '"YOUR_CLIENT_ID"'
<string name="wonderpush_clientId" translatable="false">YOUR_CLIENT_ID</string>
<meta-data android:name="com.wonderpush.sdk.clientId" android:value="YOUR_CLIENT_ID" />
Client secret
The client secret used to secure network calls.
buildConfigField 'String', 'WONDERPUSH_CLIENT_SECRET', '"YOUR_CLIENT_SECRET"'
<string name="wonderpush_clientSecret" translatable="false">YOUR_CLIENT_SECRET</string>
<meta-data android:name="com.wonderpush.sdk.clientSecret" android:value="YOUR_CLIENT_SECRET" />
Sender ID
The Firebase FCM Sender ID used to register to push notifications.
By default, the SDK will use the Sender ID of the Firebase account integrated into your app if any, or will fall back to WonderPush own Sender ID, which is convenient but cannot offer push token portability.
buildConfigField 'String', 'WONDERPUSH_SENDER_ID', '"12345678901"'
<string name="wonderpush_senderId" translatable="false">12345678901</string>
<meta-data android:name="com.wonderpush.sdk.senderId" android:value="12345678901" />
Auto init
Permits to deactivate the automatic initialization of the SDK.
The default is true
.
buildConfigField 'boolean', 'WONDERPUSH_AUTO_INIT', 'false'
<bool name="wonderpush_autoInit" translatable="false">false</bool>
<meta-data android:name="com.wonderpush.sdk.autoInit" android:value="false" />
Logging
Controls debug logging.
The default is false
.
You can enable it for debug builds but you should disable it for release builds.
buildConfigField 'boolean', 'WONDERPUSH_LOGGING', 'true'
<bool name="wonderpush_logging" translatable="false">true</bool>
<meta-data android:name="com.wonderpush.sdk.logging" android:value="true" />
Requires user consent
Controls whether user consent is required before doing anything.
The default is false
.
buildConfigField 'boolean', 'WONDERPUSH_REQUIRES_USER_CONSENT', 'true'
<bool name="wonderpush_requiresUserConsent" translatable="false">true</bool>
<meta-data android:name="com.wonderpush.sdk.requiresUserConsent" android:value="true" />
Geolocation
Controls whether geolocation is collected or not.
The default is true
.
buildConfigField 'boolean', 'WONDERPUSH_GEOLOCATION', 'false'
<bool name="wonderpush_geolocation" translatable="false">false</bool>
<meta-data android:name="com.wonderpush.sdk.geolocation" android:value="false" />
You can control this dynamically inside the application by calling enableGeolocation()
or disableGeolocation()
at anytime.
Disabling geolocation as shown above simply calls either the one or the other before initializing the SDK.
Subscribing users
subscribeToNotifications
subscribeToNotifications
Subscribes to push notifications.
Android does not require user explicit permission, so users are subscribed to push notifications by default.
You must wait before an activity has been resumed before calling this method. Calling this method from your Application's
onCreate
method will not work.
// Shows the push permission prompt when necessary
WonderPush.subscribeToNotifications();
// You can also use this variation that will show an alert dialog
// to users who have repeatedly denied the permission, taking them to the settings
// of your app where they can flip the permission switch:
WonderPush.subscribeToNotifications(true);
unsubscribeFromNotifications
unsubscribeFromNotifications
Unsubscribes from push notifications.
This method marks the user as soft opt-out.
isSubscribedToNotifications
isSubscribedToNotifications
Returns a boolean indicating whether the user is subscribed to push notifications.
Returns false
if user consent is required and not granted.
Segmentation
Segmentation functions allow you to mark installations so they can be added to segments and you can send them targeted notifications later.
There are many ways of performing segmentation:
Tags are like labels you can stick on users. Use tags to create segments in your dashboard and send targeted push notifications. Example: all users that have the "customer" tag.
Events have a date, a type
of your choice and attributes
. Use events to create segments in your dashboard and send targeted push notifications. Example: all users that purchased in the last hour is a typical event-based segment.
Installation properties represent traits of the user. That's a good place to store age, gender and other data traditionally used for segmentation. Create property-based segments in your dashboard. Example: all users above 18 is a typical property-based segment.
trackEvent
trackEvent
Tracks a custom event of your choice. E.g. purchase
.
Parameter | Type | Description |
---|---|---|
type | String | Required The type of the event to track. Event names starting with @ are reserved for internal use and cannot be used here. |
attributes | JSONObject | Attributes associated with this event. See format of property names for detailed syntax. |
Example:
JSONObject attributes = new JSONObject();
attributes.put("string_product", "Some product");
attributes.put("float_price", 1.99);
WonderPush.trackEvent("purchase", attributes);
addTag
addTag
Adds one or more tags to the current installation.
WonderPush.addTag("customer");
WonderPush.addTag("economics", "sport", "politics");
removeTag
removeTag
Removes one or more tags from the current installation.
WonderPush.removeTag("customer");
WonderPush.removeTag("economics", "sport", "politics");
removeAllTags
removeAllTags
Removes all tags from the current installation.
hasTag
hasTag
Tests whether a given tag is attached to the current installation.
if (WonderPush.hasTag("customer")) {
// Display paid features
}
getTags
getTags
Returns all the tags attached to the current installation as an Set<String>
.
getPropertyValue
getPropertyValue
Returns the value of a given property associated to the current installation.
If the property stores an array, only the first value is returned. This way you don't have to deal with potential arrays if that property is not supposed to hold one. Returns JSONObject.NULL
instead of null
if the property is absent or has an empty array value.
Object value = WonderPush.getPropertyValue("string_lastname");
// You should always check the type of the returned value, especially as `JSONObject.NULL` is used when there is no value
if (value instanceof String) {
String lastName = (String) value;
// Use lastName
}
getPropertyValues
getPropertyValues
Returns an immutable list of the values of a given property associated to the current installation.
If the property does not store an array, a list is returned nevertheless. This way you don't have to deal with potential scalar values if that property is supposed to hold an array. Returns an empty list instead of JSONObject.NULL
or null
if the property is absent. Returns a list wrapping any scalar value held by the property.
Note, the returned value is an immutable list.
List<Object> values = WonderPush.getPropertyValues("string_favoritePlayers");
// Note: values is immutable
// Depending on what you want to accomplish, you may find it useful to check the type of each individual value like follows
List<String> favoritePlayers = new ArrayList<>();
for (Object value : values) {
// You should always check the type of the returned value, especially as `JSONObject.NULL` represents nulls
if (value instanceof String) {
favoritePlayers.add((String) value);
}
}
addProperty
addProperty
Adds the value to a given property associated to the current installation.
The stored value is made an array if not already one. If the given value is an array, all its values are added. If a value is already present in the stored value, it won't be added.
See format of property names for detailed syntax.
// You can add a single value
WonderPush.addProperty("string_interests", "sport");
// You can add an array of values
WonderPush.addProperty("string_interests", new String[] { "sport", "entertainment" });
// You can add a collection of values
List<String> interestsToAdd = ...;
WonderPush.addProperty("string_interests", interestsToAdd);
removeProperty
removeProperty
Removes the value from a given property associated to the current installation.
The stored value is made an array if not already one. If the given value is an array, all the given values are removed, even if it is present multiple times.
// You can remove a single value
WonderPush.removeProperty("string_interests", "sport");
// You can remove an array of values
WonderPush.removeProperty("string_interests", new String[] { "sport", "entertainment" });
// You can remove a collection of values
List<String> interestsToRemove = ...;
WonderPush.removeProperty("string_interests", interestsToRemove);
setProperty
setProperty
Sets the value to a given property associated to the current installation.
The previous value is replaced entirely. The value can be a String
, Boolean
, Number
(coerced to Long
or Double
), JSONObject
, JSONArray
, or JSONObject.NULL
(which has the same effect as unsetProperty). In fact, this function accepts any value supported by JSONObject.wrap()
, like Map
, Collection
, and arrays.
See format of property names for detailed syntax.
// You can set a single value
WonderPush.setProperty("bool_isCustomer", true);
// You can remove a field using null or JSONObject.NULL
WonderPush.setProperty("int_age", null);
// You can set an array of values
WonderPush.setProperty("string_interests", new String[] { "sport", "entertainment" });
// You can set a collection of values
List<String> followedPlayers = ...;
WonderPush.setProperty("string_followedPlayers", followedPlayers);
unsetProperty
unsetProperty
Removes the value of a given property associated to the current installation.
The previous value is replaced with JSONObject.NULL
.
WonderPush.unsetProperty("string_favoritePlayers");
putProperties
putProperties
Updates the properties of the current installation. Omitting a previously set property leaves it untouched. To remove a property, you must pass it explicitly with a value of JSONObject.NULL
.
Parameter | Type | Description |
---|---|---|
properties | Object | Properties to add or update. See format of property names for detailed syntax. |
Example:
JSONObject properties = new JSONObject();
properties.put("int_age", 34);
WonderPush.putProperties(properties);
getProperties
getProperties
Returns a JSONObject
containing the properties of the current installation.
For example:
JSONObject properties = WonderPush.getProperties();
String name = properties.optString("string_name");
getCountry
getCountry
Returns the user's country, either as previously stored, or as guessed from the system.
setCountry
setCountry
Overrides the user's country.
Defaults to getting the country code from the system default locale.
You should use an ISO 3166-1 alpha-2 country code, eg: US
, FR
, GB
.
Use null
to disable the override.
getCurrency
getCurrency
Returns the user's currency, either as previously stored, or as guessed from the system.
setCurrency
setCurrency
Overrides the user's currency.
Defaults to getting the currency code from the system default locale.
You should use an ISO 4217 currency code, eg: USD
, EUR
, GBP
.
Use null
to disable the override.
getLocale
getLocale
Returns the user's locale, either as previously stored, or as guessed from the system.
setLocale
setLocale
Overrides the user's locale.
Defaults to getting the language and country codes from the system default locale.
You should use an xx-XX
form of RFC 1766, composed of a lowercase ISO 639-1 language code, an underscore or a dash, and an uppercase ISO 3166-1 alpha-2 country code.
Use null
to disable the override.
getTimeZone
getTimeZone
Returns the user's time zone, either as previously stored, or as guessed from the system.
setTimeZone
setTimeZone
Overrides the user's time zone.
Defaults to getting the time zone code from the system default locale.
You should use an IANA time zone database codes, Continent/Country
style preferably like Europe/Paris
, or abbreviations like CET
, PST
, UTC
, which have the drawback of changing on daylight saving transitions.
Use null
to disable the override.
setUserId
setUserId
Assigns your own user ID to an installation. See User IDs.
WonderPush.setUserId("YOUR_OWN_USER_ID");
getUserId
getUserId
Returns the user ID you've assigned to this installation if any.
Installation info
getInstallationId
getInstallationId
Returns a string representing the installationId identifying this installation in your application.
getPushToken
getPushToken
Returns a string representing the push token (device token) for this device.
Privacy
setRequiresUserConsent
setRequiresUserConsent
Sets whether user consent is required before the SDK takes any action.
Calling this method with true
is only useful if you do not use the automatic initialization, otherwise you should rather use the Requires user consent
configuration option. You can also set the latter to true
and later call this function with false
if your application detects that this restriction is not necessary.
If you do not use the automatic initialization, call this method before initializing the SDK.
By default, user consent is not required.
Note that the value is not remembered between runs, it is rather a mode that you enable.
getUserConsent
getUserConsent
Gets user privacy consent.
See setUserConsent
below.
setUserConsent
setUserConsent
Sets user privacy consent.
Works in conjunction with the Requires user consent
configuration option and the setRequiresUserConsent
method.
If user consent is required, the SDK takes no action until user consent it provided by calling setUserConsent(true)
. Calling setUserConsent(false)
blocks the SDK again.
disableGeolocation
disableGeolocation
Disables the collection of the user's geolocation.
You can call this method before initializing the SDK.
enableGeolocation
enableGeolocation
Enables the collection of the user's geolocation.
You can call this method before initializing the SDK.
You still need the appropriate geolocation permissions in your AndroidManifest.xml to be able to read the user's location.
setGeolocation
setGeolocation
Overrides the user's geolocation.
You can call this method before initializing the SDK.
Using this method you can have the user's location be set to wherever you want.
This may be useful to use a pre-recorded location.
Note that the value is not persisted.
Calling this method with null
has the same effect as calling disableGeolocation()
.
clearEventsHistory
clearEventsHistory
Instructs to delete any event associated with the all installations present on the device, locally and on WonderPush servers.
clearPreferences
clearPreferences
Instructs to delete any custom data (including installation properties) associated with the all installations present on the device, locally and on WonderPush servers.
clearAllData
clearAllData
Instructs to delete any event, installation and potential user objects associated with all installations present on the device, locally and on WonderPush servers.
downloadAllData
downloadAllData
Initiates the download of all the WonderPush data relative to the current installation, as a zipped JSON. This method is blocking and starts a sharing intent with the created file.
Delegate interface
setDelegate
setDelegate
Sets the delegate for the WonderPushSDK. Setting the delegate lets you control various behaviors of the WonderPushSDK at runtime.
It is advised to set the delegate as early as possible, in your Application
class.
See the following methods for details on what the delegate can do.
urlForDeepLink
urlForDeepLink
Lets you overwrite URLs that WonderPush will open. This method is called with an object describing the deep link to open as parameter and returns a String
URL that WonderPush will use to create the fired Intent.
public class MyDelegate extends WonderPushAbstractDelegate {
@Override
public String urlForDeepLink(DeepLinkEvent event) {
return event.getUrl();
}
}
Broadcast intents
Broadcast notification clicked
When a notification is clicked whose action is to open the special URL wonderpush://notificationOpen/broadcast
, our SDKs forward this click to your app or website without taking any other action.
Such notifications can be created from the online dashboard by choosing the option to Let application code decide from the compose tab of the notification edition interface.
You can listen to these clicks and decide what to do by adding a small amount of code.
LocalBroadcastManager.getInstance(this).registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (!WonderPush.INTENT_NOTIFICATION_WILL_OPEN_EXTRA_NOTIFICATION_TYPE_DATA.equals(
intent.getStringExtra(WonderPush.INTENT_NOTIFICATION_WILL_OPEN_EXTRA_NOTIFICATION_TYPE))) {
Intent pushNotif = intent.getParcelableExtra(WonderPush.INTENT_NOTIFICATION_WILL_OPEN_EXTRA_RECEIVED_PUSH_NOTIFICATION);
Log.d("WonderPush", pushNotif.toString());
}
}
}, new IntentFilter(WonderPush.INTENT_NOTIFICATION_WILL_OPEN));
Popups (formerly known as In-app messaging)
Popups methods are located on the InAppMessaging.getInstance()
object.
setMessageDisplayComponent
setMessageDisplayComponent
Setting the message display component lets you handle the display of popups yourself via an object that implements the InAppMessagingDisplay interface.
import com.wonderpush.sdk.inappmessaging.InAppMessaging;
// ...
InAppMessaging.getInstance().setMessageDisplayComponent(new InAppMessagingDisplay() {
// Implement
});
See handling the display of popups yourself for details on how to implement the message display component.
setMessagesSuppressed
setMessagesSuppressed
The setMessageDisplaySuppressed
method can be called with true
to prevent the display of any popup. Calling this method with false
permits such display again. By default, display is allowed.
import com.wonderpush.sdk.inappmessaging.InAppMessaging;
// ...
InAppMessaging.getInstance().setMessagesSuppressed(true);
addImpressionListener
addImpressionListener
The addImpressionListener
lets you specify an InAppMessagingImpressionListener
called each time a popup is displayed:
InAppMessaging.getInstance().addImpressionListener(new InAppMessagingImpressionListener() {
@Override
public void impressionDetected(@NonNull InAppMessage inAppMessage) {
// impression detected
}
});
addClickListener
addClickListener
The addClickListener
method lets you specify an InAppMessagingClickListener
called each time a popup is clicked:
InAppMessaging.getInstance().addClickListener(new InAppMessagingClickListener() {
@Override
public void messageClicked(@NonNull InAppMessage inAppMessage, @NonNull List<ActionModel> actions) {
// click detected
}
});
addDisplayErrorListener
addDisplayErrorListener
The addDisplayErrorListener
method lets you specify an InAppMessagingDisplayErrorListener
called each time a popup display error occurs:
InAppMessaging.getInstance().addDisplayErrorListener(new InAppMessagingDisplayErrorListener() {
@Override
public void displayErrorEncountered(@NonNull InAppMessage inAppMessage, @NonNull InAppMessagingDisplayCallbacks.InAppMessagingErrorReason errorReason) {
// error detected
}
});
Updated over 1 year ago