Documentation: Push Notifications Onsite Messaging REST API
  1. Documentation
  2. Android App Push Notification
  3. Android SDK Reference

Android SDK Reference

PushAlert Android Native SDK Reference

Just starting with Android SDK?

Check out our Android Setup SDK Guide

Parameter Data Type Description
Debugging
enableDebug Method Enable/Disable logging to help debug PushAlert implementation.
Initialization
init Method Initialises PushAlert. It should be called from the onCreate method of your Application class.
setDefaultAccentColor Method To set the default accent color of a notification.
setDefaultSmallIcon Method To set the default small icon.
customizeTwoStep Method To customize the 2 step opt-in dialog text, icons and colors.
setInAppNotificationBehaviour Method To set in app behaviour, when your app is in focus.
setNotificationOpener Handler To set your notification click handler, you can open your app using extra data or url inside your app.
setNotificationReceiver Handler To set your own notification receiver, you can modify color, text etc. or use extra data as per your need.
setOnSubscribeListener Handler To set your listener when a user subscribes, this will help you to associate subscription id with your database.
unsubscribeWhenNotificationsAreDisabled Method If notifications are disabled for your app, unsubscribe the user.
setRequiresPrivacyConsent Method To set whether privacy consent is required to enable notifications.
enableFirebaseEventReporting Method Send events to Google Analytics to track your campaign performance.
enableLocationSharing Method To enable location sharing, requires ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission.
Pre-defined Subscriber Properties
associateID Method To associate a subscriber with a particular unique id (your logic), can be used to send notification to a particular subscriber.
setEmail Method To set the email of the push subscriber.
setFirstName Method To set the first name of the push subscriber.
setLastName Method To set the last name of the push subscriber.
setGender Method To set the gender of the push subscriber.
setAge Method To set the age of the push subscriber.
setPhoneNum Method To set the phone number of the push subscriber.
Segments, Attributes and Trigger Events
addUserToSegment Method To add a subscriber to a segment.
removeUserFromSegment Method To remove a subscriber from a segment.
addAttributes Method To add custom attributes to a subscriber.
triggerEvent Method To send notification on custom events. Events are user interactions within your app.
e-Commerce
processAbandonedCart Method Add, update or remove abandoned cart notification.
addOutOfStockAlert Method To add an out of stock alert for a product.
isOutOfStockEnabled Method Check whether an out of stock alert is enabled for a product.
removeOutOfStockAlert Method To remove the out of stock alert of a product.
addPriceDropAlert Method To add a price drop alert for a product.
isPriceDropEnabled Method Check whether the price drop alert is enabled for a product.
removePriceDropAlert Method To remove the price drop alert of a product.
Privacy
setUserPrivacyConsent Method If privacy consent is required then call this method with user consent to enable notifications.
getUserPrivacyConsent Method Check whether user consent for allowing notification is set to true or not.
getRequiresPrivacyConsent Method Check whether privacy consent required is enabled.
Subscriber Status
getSubscriberID Method Get the subscriber id, can be used to associate with the user details in your own database.
isUserSubscribed Method Check whether the user is subscribed.
isNotificationDisabled Method To check whether subscribers turned off notifications (not at system level).
disableNotification Method To disable/enable notifications for a subscriber (not at system level).
Conversion Reporting
reportConversion Method Report conversions without a value like register or sign-up.
reportConversionWithValue Method Report conversions with value (like purchase).
Opt-in
requestForPushNotificationPermission Method To initiate push notification permission manually.
setOptInMode Method To set the opt-in mode - Auto, Manual, 2-Step.

Debugging

enableDebug

Enable logging to help debug any issue while setting up PushAlert on Android. This method is static, so you can call it before PushAlert init.

Parameters Type Description
enable boolean Set true to enable.
//This will enable the debug mode.
PushAlert.enableDebug(true);
//This will enable the debug mode.
PushAlert.enableDebug(true)
Copy

Initialization

init

Initialises PushAlert to register the device for push notifications. Should be called in the onCreate method of your Application class.

Parameters Type Description
appId String Your PushAlert App ID, available at Dashboard->Settings->App
context Context Your application context
import co.pushalert.PushAlert;
import android.os.Build;

public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        // PushAlert Initialization, you can get App ID from PushAlert Dashboard, Settings->App
        PushAlert.init("PUSHALERT_APP_ID", getApplicationContext());
    }
}
Copy

setDefaultAccentColor

To set the default accent color in ARGB format, will be used if no accent color is mentioned while sending a notification.

Parameters Type Description
color int Color resource ID, for e.g. R.color.accent_color. Default color resource is #ff0d82e5.
//Setting default accent color
PushAlert.init("PUSHALERT_APP_ID", getApplicationContext())
         .setDefaultAccentColor(R.color.accent_color);
Copy

setDefaultSmallIcon

To set the default small icon (preferably small icon of your app), will be used if no small icon is mentioned while sending a notification. Android only uses the alpha channel for the small icon and displays a monochrome icon with an accent color applied on it.

Parameters Type Description
icon int Drawable resource ID, for e.g. R.drawable.small_icon. Default small icon is a bell icon.#ff0d82e5.
//Setting default small icon for notification
PushAlert.init("PUSHALERT_APP_ID", getApplicationContext())
         .setDefaultAccentColor(R.color.accent_color);
Copy

customizeTwoStep

With Android 13, you can't send notifications without getting consent from the user. Two step opt-in helps your app users to know why they should subscribe to Push Notifications. With this function you can change the title, sub-title along with accept button, reject button properties including color, text and background color.

Parameters Type Description
twoStepHelper TwoStepHelper You can set the following values by overriding the setValues() method.
  • title (String): Title of the dialog. Default: "Get Notified"
  • titleTextColor (int): Color drawable resource for title text. Default: #ffffff (white)
  • subTitle (String): Subtitle of the dialog, to explain why the user should subscribe to Push Notifications. Default: "Enable notification to get important updates instantly"
  • subTitleTextColor (int): Color drawable resource for sub-title text. Default: #000000 (black)
  • acceptBtn (String): Accept Button text. Default: "I'm in"
  • acceptBtnTextColor (int): Color drawable resource for accept button text. Default: #000000 (black)
  • acceptBtnBgColor (int): Color drawable resource for accept button background. Default: #1a73e8
  • rejectBtn (String): Reject Button text. Default: "Skip"
  • rejectBtnTextColor (int): Color drawable resource for reject button text. Default: #1a73e8
  • rejectBtnBgColor (int): Color drawable resource for reject button background. Default: transparent
  • iconDrawable (int): Image drawable resource that represents notification icon. Default: A Golden Bell Icon
  • imageDrawable (int): Image drawable resource that represents notification. Default: Two notifications one below another.
//Customizing 2-Step Opt-in
PushAlert.init("PUSHALERT_APP_ID", getApplicationContext())
         .customizeTwoStep(new TwoStepHelper() {
            @Override
            public void setValues() {
                title = "Want to stay Updated?";
                titleTextColor = R.color.title_color;

                subTitle = "Enable notification to get important updates instantly";
                subTitleTextColor = R.color.sub_title_color;

                acceptBtn = "Yes";
                acceptBtnTextColor = R.color.accept_btn_color;
                acceptBtnBgColor = R.color.accept_btn_bg_color;

                rejcectBtn = "No";
                rejcectBtnTextColor = R.color.reject_btn_color;
                rejcectBtnBgColor = R.color.reject_btn_bg_color;

                iconDrawable = R.drawable.notification_icon;
                imageDrawable = R.drawable.notification_image;
            }
        });
Copy

setInAppNotificationBehaviour

To set in app behaviour, whether to show notification when your app is in focus.

Parameters Type Description
inAppBehaviour PAInAppBehaviour
  • NONE: Don't show notification when your app is in focus.
  • NOTIFICATION: Show notification when your app is in focus. Default
//Setting in-app behaviour (when app in focus) of notifications
PushAlert.init("PUSHALERT_APP_ID", getApplicationContext())
         .setInAppNotificationBehaviour(PushAlert.PAInAppBehaviour.NOTIFICATION);
Copy

setNotificationOpener

Sets a notification opener handler. It will be called when a notification is tapped. If this method is used, the default behaviour of opening the url will be overridden. You can use action id, extra data or url to directly open the particular part of the app.

Parameters Type Description
notificationOpener NotificationOpener
    Instance of the class implementing this interface.
//Setting in-app behaviour (when app in focus) of notifications
PushAlert.init("PUSHALERT_APP_ID", getApplicationContext())
         .setNotificationOpener(new NotificationOpener() {
            @Override
            public void notificationOpened(PANotificationOpened paNotificationOpened) {
                int notification_id = paNotificationOpened.getNotificationId();
                String action_id = paNotificationOpened.getActionId();
                String url = paNotificationOpened.getUrl();
                JSONObject extras = paNotificationOpened.getExtraData();

                //Use above data to open particular part of the app
                //Use action_id (clicked action button) to perform particular action like adding to cart, favourite, like, dislike
            }
        });
Copy

setNotificationReceiver

To set your own notification receiver. You can modify color, text and use extra data as per your requirements. You can also prevent a notification from being shown.

Parameters Type Description
notificationReceiver NotificationReceiver
    Instance of the class implementing this interface.
//Setting in-app behaviour (when app in focus) of notifications
PushAlert.init("PUSHALERT_APP_ID", getApplicationContext())
         .setNotificationReceiver(new NotificationReceiver() {
            @Override
            public boolean notificationReceived() {
                PANotification paNotification = getPANotification();
                //Use PANotification object to get all properties of the notification like getShortTitle, getContent(), getImage() etc
                //These properties can be modified here

                //Return true if you handled the notification and don't want to PushAlert to show notification in the shade
                return false;
            }
        });
Copy

setOnSubscribeListener

Set your listener to when a user subscribes, this will help you to associate the subscriber id with user details in your database. You can further use this subscriber id to send notifications to a particular user as well as other operations using REST API.

Parameters Type Description
onSubscribeListener PASubscribe
    Instance of the class implementing this interface.
//Setting onSubscribeListener to get subscriber id on subscribe.
PushAlert.init("PUSHALERT_APP_ID", getApplicationContext())
         .setOnSubscribeListener(new PASubscribe() {
            @Override
            public void onSubscribe(String s) {
                //Save subscriber id s as per your logic
            }
        });
Copy

unsubscribeWhenNotificationsAreDisabled

Whether to unsubscribe the user if notifications are disabled in your App Settings.

Parameters Type Description
unsubscribe boolean Set true to unsubscribe the user. Default: False
//Setting to unsubscribe if users blocks notification in app settings.
PushAlert.init("PUSHALERT_APP_ID", getApplicationContext())
         .unsubscribeWhenNotificationsAreDisabled(true);
Copy

setRequiresPrivacyConsent

If set to true and the opt-in mode is not set to 2-Step, PushAlert SDK won't process the subscription. You would need to call setUserPrivacyConsent(true) after getting the consent from the user, the user will be auto-subscribed on Android 12 and below, while for Android 13 and above, they will be shown the native permission dialog.

Parameters Type Description
consentRequired boolean Set true to enable consent requirement to subscribe to push notifications. Default: False
//Setting consent required to push notification.
PushAlert.init("PUSHALERT_APP_ID", getApplicationContext())
         .setRequiresPrivacyConsent(true);
Copy

enableFirebaseEventReporting

To Enable firebase analytics reporting. Track notifications received, clicked or the impact report on your Google Analytics Dashboard.

Parameters Type Description
enable boolean Set true to send events to Google Analytics to track your campaign performance. Default: False
//To enable tracking of your campaign in Google Analytics.
PushAlert.init("PUSHALERT_APP_ID", getApplicationContext())
         .enableFirebaseEventReporting(true);
Copy

enableLocationSharing

Disable or enable location sharing data, requires ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission. You can use this information to target users based on longitude and latitude.

Parameters Type Description
enable boolean Set true to enable location sharing. Default: False
//Enabling sharing location data to target user based on longitude and latitude.
PushAlert.init("PUSHALERT_APP_ID", getApplicationContext())
         .enableLocationSharing(true);
Copy

Pre-defined Subscriber Properties

associateID

To associate a subscriber with a unique id (your logic). Can be used to send notifications to a particular subscriber or other operations using REST API.

Parameters Type Description
id String Unique ID for a subscriber
//Setting unique ID to a subscriber
PushAlert.associateID("UNIQUE_ID");
Copy

setEmail

To set the email address of the push subscriber.

Parameters Type Description
email String Email id of the subscriber
//Setting unique ID to a subscriber
PushAlert.setEmail("someone@korner.space");
Copy

setFirstName

To set the first name of the push subscriber.

Parameters Type Description
firstName String First name of the subscriber
//Setting first name of the subscriber
PushAlert.setFirstName("Alex");
Copy

setLastName

To set the last name of the push subscriber.

Parameters Type Description
lastName String Last name of the subscriber
//Setting last name of the subscriber
PushAlert.setLastName("Jones");
Copy

setGender

To set the gender of the push subscriber.

Parameters Type Description
gender String Gender of the subscriber
//Setting gender of the subscriber
PushAlert.setGender("male");
Copy

setAge

To set the age of the push subscriber.

Parameters Type Description
age int Age of the subscriber
//Setting age of the subscriber
PushAlert.setAge(29);
Copy

setPhoneNum

To set the phone number of the push subscriber.

Parameters Type Description
phoneNum String Phone number of the subscriber
//Setting phone number of the subscriber
PushAlert.setPhoneNum("(000) 000-0000");
Copy

Segments, Attributes and Trigger Events

addUserToSegment

Add a push subscriber to a segment.

Parameters Type Description
seg_id int Segment ID
//Add a subscriber to a segment
PushAlert.addUserToSegment(12404);
Copy

removeUserFromSegment

Remove a push subscriber from a segment.

Parameters Type Description
seg_id int Segment ID
//Remove a subscriber from a segment
PushAlert.removeUserFromSegment(12404);
Copy

addAttributes

Add custom attributes to a push subscriber.

Parameters Type Description
attributes Map <String, String> Attribute name, value map
//Adding attributes to a subscriber
Map<String, String> attr = new HashMap<>();
attr.put("language", "es");
attr.put("zip_code", "98125");
PushAlert.addAttributes(attr);
Copy

triggerEvent

Events are user interactions with content on your app. Examples of custom events can be a download, link click, scroll to a particular part of the page, playing a video etc. With triggerEvent you can initiate push notifications for a particular event.

Parameters Type Description
eventCategory String The object or page that was interacted with (e.g. 'Video')
eventAction String The type of interaction (e.g. 'play','pause','stopped').
eventLabel String Optional. Used for categorizing events. (e.g. 'Launch Campaign').
eventValue int Optional. A numeric value associated with the event (e.g. 2017).
//Trigger events
PushAlert.triggerEvent("videos", "play", "video_id", 132);
PushAlert.triggerEvent("pdf", "download", "Top Marketing Strategies");
Copy

E-Commerce

processAbandonedCart

Update or delete abandoned cart information which are used to send abandoned cart notifications.

Parameters Type Description
action AbandonedCartAction
  • UPDATE: Updates the abandoned cart data.
  • DELETE: Removes abandoned cart information.
data Map <String, String> Cart information in key, value map
//Updating cart information for abandoned cart notifications, this can be called whenever there are changes in cart
Map<String, String> data = new HashMap<>();
data.put("customer_name", "Alex");
data.put("image", "https://cdn.pushalert.co/large-image/image9-16_test.png");
data.put("total_items", "3");
data.put("total_amount", "12.99");
data.put("cart_url", "https://korner.space/blog/cart/");
data.put("checkout_url", "https://korner.space/blog/checkout/");

PushAlert.processAbandonedCart(PushAlert.AbandonedCartAction.UPDATE, data);


//Deleting cart information to remove abandoned cart notifications from the queue, you can call this on order completion or when cart is emptied.
PushAlert.processAbandonedCart(PushAlert.AbandonedCartAction.DELETE, null);
Copy

addOutOfStockAlert

Subscribe the user to a back in stock alert for a specific product. When the product comes back in stock a notification will be sent.

Parameters Type Description
product_id int Product ID
variant_id int Variant id of the given product.
price double Price of the product for the given variant.
extras Map <String, String> Extra information in key, value map
//Adding in-stock alert for a subscriber
Map<String, String> map = new HashMap<>();
map.put("name", "Alex");

PushAlert.addOutOfStockAlert(2432, 1, 19.99, map);
Copy

isOutOfStockEnabled

Check whether the out of stock alert is enabled for a given variant of the product.

Parameters Type Description
product_id int Product ID
variant_id int Variant id of the given product.
//Checking out of stock alert is enabled for a given variant of the product.
boolean isEnabled = PushAlert.isOutOfStockEnabled(2432, 1);
Copy

removeOutOfStockAlert

To remove out of stock alerts for a given variant of the product for a push subscriber.

Parameters Type Description
product_id int Product ID
variant_id int Variant id of the given product.
//Removing out of stock alert for a given variant of the product.
PushAlert.removeOutOfStockAlert(2432, 1);
Copy

addPriceDropAlert

Add a price drop alert for a particular product for a subscriber. When the product price goes down a notification will be sent.

Parameters Type Description
product_id int Product ID
variant_id int Variant id of the given product.
price double Price of the product for the given variant.
extras Map <String, String> Extra information in key, value map
//Adding price drop alert for a subscriber
Map<String, String> map = new HashMap<>();
map.put("name", "Alex");

PushAlert.addPriceDropAlert(2432, 1, 19.99, map);
Copy

isPriceDropEnabled

Check whether a price drop alert is enabled for a given variant of the product.

Parameters Type Description
product_id int Product ID
variant_id int Variant id of the given product.
//Checking price drop alert is enabled for a given variant of the product.
boolean isEnabled = PushAlert.isPriceDropEnabled(2432, 1);
Copy

removePriceDropAlert

To remove price drop alerts for a given variant of the product for a push subscriber.

Parameters Type Description
product_id int Product ID
variant_id int Variant id of the given product.
//Removing price drop alert for a given variant of the product.
PushAlert.removePriceDropAlert(2432, 1);
Copy

Privacy

setUserPrivacyConsent

If setRequiresPrivacyConsent is set to true then you need to call this method after taking consent from the user to enable notifications.

Parameters Type Description
privacyConsent boolean Set true after user consent.
//Setting true after getting user consent.
PushAlert.setUserPrivacyConsent(true);
Copy

getUserPrivacyConsent

Check whether user consent for allowing notification is set to true or not. Returns a boolean.

//Checking user consent to allow notification.
boolean userConsent = PushAlert.getUserPrivacyConsent();
Copy

getRequiresPrivacyConsent

Check whether setRequiresPrivacyConsent is set to true. Returns a boolean.

//Checking consent required or not.
boolean requiresConsent = PushAlert.getRequiresPrivacyConsent();
Copy

Subscriber Status

getSubscriberID

Get subscriber id of the user (null if not subscribed). Returns a String.

//Getting PushAlert subscriber ID.
String subs_id = PushAlert.getSubscriberID();
Copy

isUserSubscribed

Check whether the user subscribed. Returns a boolean.

//Checking push subscription status.
boolean isUserSubscribed = PushAlert.isUserSubscribed();
Copy

disableNotification

To disable/enable notifications for a push subscriber. This does not unsubscribe the user. You can use this method to give an option to the user in your app preferences.

Parameters Type Description
disable boolean Set true to disable notification for the subscriber.
//Disable notification for the subscriber.
PushAlert.disableNotification(true);
Copy

isNotificationDisabled

Check whether notifications are disabled by a subscriber (not at system level, by using method disableNotification). Returns a boolean.

//Checking notification status.
boolean isNotificationDisabled = PushAlert.isNotificationDisabled();
Copy

Conversion Reporting

reportConversion

Report a conversion without a value like register, video played, sign-up etc. This will associate the notification with conversion, and help you to analyze your goal.

Parameters Type Description
conversion_name String Conversion name like register, download
//Reporting conversion without a value.
PushAlert.reportConversion('register');
Copy

reportConversionWithValue

Report a conversion with a value for e.g., purchase with a numeric value 9.99. This will associate the notification with conversion, and help you to analyze them.

Parameters Type Description
conversion_name String Conversion name like purchase
conversion_value double Conversion value like 12.99
//Reporting conversion with a value.
PushAlert.reportConversionWithValue('purchase', 12.99);
Copy

Opt-in

setOptInMode

To set opt-in mode - Auto, Manual or 2-Step

Parameters Type Description
optInMode PAOptInMode
  • AUTO: If previously, permission was denied then 2-Step opt-in will be used, otherwise direct permission.
  • MANUAL: You need to call method requestForPushNotificationPermission to initiate push subscription.
  • TWO_STEP: 2-Step opt-in will be used. If the user accepts in the 1st step, the user will be auto-subscribed on Android 12 and below, while for Android 13 and above, they will be shown the native permission dialog.
// Set Opt-in Mode for Android
// From Android 13 and above, request permission is required to send push notifications. We recommend TWO_STEP opt-in mode for Android 13 and above; otherwise AUTO opt-in mode.
if (Build.VERSION.SDK_INT >= 33){
    PushAlert.setOptInMode(PushAlert.PAOptInMode.TWO_STEP);
}
else{
    PushAlert.setOptInMode(PushAlert.PAOptInMode.AUTO);
}
Copy

requestForPushNotificationPermission

To initiate the push notification permission process manually. Returns true, if already subscribed.

Parameters Type Description
direct boolean Set true to bypass any opt-in mode, else will use opt-in mode defined by setOptInMode
//Initialising push subscription manually
PushAlert.requestForPushNotificationPermission(true);
Copy