PushService

The PushService object allows you to leverage the BlackBerry push architecture to receive push data in your application.

The push solution includes a push-enabled application on a BlackBerry device and a content provider's server-side application (also known as the Push Initiator). The Push Initiator can deliver up to 8 kB of content (images, text, and so on) and headers (metadata name-value pairs) using a Push Proxy Gateway (PPG).

Two PPGs are available: the public/BlackBerry Internet Service (BIS) PPG and the enterprise/BlackBerry Enterprise Server (BES) PPG. The PushService object allows your application to receive push messages sent through either of these PPGs.

To work with a PushService object, you must first call the static create function. On a successful create, you are then able to perform operations using the PushService object you receive in the success callback.

Installation:

To use this API in your project, add the push plugin:

webworks plugin add com.blackberry.push

As of BlackBerry 10 WebWorks SDK 2.1, there is a change in behavior when you add this plugin. Previously, when you added the com.blackberry.push plugin to your project, the tools automatically added the _sys_use_consumer_push permission. However, automatically adding this permission caused problems for enterprise push applications. As a result, the permission is no longer automatically added. If you want to access consumer push functionality, you must now explicitly add this permission by either using the SDK web tool or manually editing the config.xml file.

Learning Resources:

Sample - Push Capture Basics Sample that demonstrates how to use the BlackBerry Push API. [BlackBerry on GitHub]

Sample - Push Capture More extensive sample that demonstrates how to use the BlackBerry Push API. Uses bbui.js. [BlackBerry on GitHub]

Developer Guide for creating a Push Capture sample app [BlackBerry Developer Documentation].

create()

Creates a PushService object. The PushService object will only be available if the successCallback function is called. It will not be available if the failCallback function is called instead.

Synopsis:

void PushService.create(options, successCallback, failCallback, simChangeCallback, pushTransportReadyCallback)

Parameters:

Options {Object}

Object literal that allows the user to specify various options.

invokeTargetID {String}

Your application's unique invoke target ID, as set in your config.xml, related to when a new push notification is received and the application needs to be invoked.

appID {String}

The provider application ID. If writing a consumer application, this corresponds to the application ID you received after registering to use the public/BIS PPG push service. If writing an enterprise application, you have the choice of not specifying appId (in which case a unique one will be generated for you under the covers) or specifying a unique value of your choosing (this second option is useful if you plan to subscribe with the Push Initiator in your application).

ppgURL {String}

The PPG URL to register with. If writing a consumer application, you will be provided with this URL after registering to use the public/BIS PPG push service. The URL will point to either the eval or the production environment (for eval, http://cp{cpid}.pushapi.eval.blackberry.com; for production, http://cp{cpid}.pushapi.na.blackberry.com where {cpid} is replaced with your content provider ID). If writing an enterprise application, no ppgUrl value should be specified.

successCallback {Function}

The callback that is invoked when the create operation is successful

pushService {PushService}

The PushService object that can be used on a successful create operation.

failCallback {Function}

The callback that is invoked when the create operation has failed.

result {Number}

The reason for the failure. See the constants provided to see what result codes apply for this operation.

simChangeCallback {Function}

The callback that is invoked when a SIM card change has occurred. This callback only applies on a successful create. When a SIM card change occurs, the channel will automatically be destroyed since this scenario may indicate the possibility of a new user using the device. Care should be taken by the application to handle this situation as well. For example, the application may wish to re-authenticate the user with the Push Initiator (if your Push Initiator implementation supports subscription) and then re-create the channel using createChannel.

pushTransportReadyCallback {Function}

The callback that is invoked after a create channel or destroy operation has failed with a result error code of either PUSH_TRANSPORT_UNAVAILABLE or PPG_SERVER_ERROR and the network/push transport/PPG is now available again.

lastFailedOperation

The last operation that was performed that failed with a result error code of either PUSH_TRANSPORT_UNAVAILABLE or PPG_SERVER_ERROR. It should be one of CREATE_CHANNEL_OPERATION or DESTROY_CHANNEL_OPERATION. Use this value to determine which operation should be tried again.

Throws:

{String}

An exception is thrown if create is called more than once with different values for options.invokeTargetId and/or options.appId.

Example:

<script type="text/javascript">

    // For a consumer application (using the public/BIS PPG)
    var ops = { invokeTargetId : 'com.sample.pushtest.target',
                appId : 'appId1',
                ppgUrl : 'http://cp123.pushapi.na.blackberry.com' };

    // For an enterprise application (using the enterprise/BES PPG)
    // var ops = { invokeTargetId : 'com.sample.pushtest.target' };

    // Or, for an enterprise application with an application ID:
    // var ops = { invokeTargetId : 'com.sample.pushtest.target',
    //             appId : 'appId1' };

    try {
        blackberry.push.PushService.create(ops,
            successCallback,
            failCallback,
            simChangeCallback,
            pushTransportReadyCallback);
    } catch (err) {
        console.log("Create was called more than once with different "
            + "values for options.invokeTargetId or options.appId.");
        console.log(err);
    }

    function successCallback(pushService) {
        // The create operation was a success
        // Save the pushService object to a global variable
        // Now, use the pushService object to now perform a
        // launchApplicationOnPush, createChannel, destroyChannel, etc.
        pushService.createChannel(createChannelCallback);
    }

    function failCallback(result) {
        // The create operation failed
        // You should compare the result code against the error
        // constants in this PushService class that apply for
        // create and take the recommended action for that constant
        if (result === blackberry.push.PushService.INTERNAL_ERROR) {
            // Retry the create up to a certain number of attempts
            // and then display an error to the user
        }
        // ... handle the other possible error constants
        // from the PushService class
    }

    function simChangeCallback() {
        // The SIM card was changed and the channel has been
        // destroyed since a new user might be using the device.
        // It is recommended that the user of this application be
        // re-authenticated with the Push Initiator (if your
        // Push Initiator implementation supports subscription)
        // followed by a call to createChannel.
    }

    function pushTransportReadyCallback(lastFailedOperation) {
        // This callback will be called when a create channel
        // or destroy channel was previously attempted and it
        // failed with a PUSH_TRANSPORT_UNAVAILABLE or a
          // PPG_SERVER_ERROR error code and now the
        // network/push transport/PPG is available again.
        // The operation indicated by lastFailedOperation should
        // be retried again.
        if (lastFailedOperation ===
            blackberry.push.PushService.CREATE_CHANNEL_OPERATION) {
            pushService.createChannel(createChannelCallback);
        } else if (lastFailedOperation ===
           blackberry.push.PushService.DESTROY_CHANNEL_OPERATION) {
           pushService.destroyChannel(destroyChannelCallback);
        }
    }

</script>
            

createChannel()

Creates a push channel for the given application. Once a channel is created, it will survive application restarts and therefore does not necessarily need to be called on every application start up. However, for a consumer application, since it is possible for the public/BIS PPG to destroy a channel under certain circumstances it may be advisable to periodicially re-create the channel (e.g. once a month). A successful create must have been done before calling this function. This function should be called in order for an application to be able to start receiving pushes. If a destroyChannel call is then made, no pushes will be able to be received until a createChannel call is made again.

Synopsis:

void PushService.createChannel(createChannelCallback)

Parameters:

createChannelCallback {Function}

The callback that is invoked when the result of the create channel operation is received.

result {Number}

The create channel operation result. See the constants provided to see what result codes apply for this operation.

token {String}

On a successful create channel operation (result ofSUCCESS), a token is returned. This token must then be communicated back to the content provider's server-side application (the Push Initiator). This token is then used by the content provider as the means to address the application on the device when initiating a push request to the PPG.

Example:

<script type="text/javascript">

    pushService.createChannel(createChannelCallback);

    function createChannelCallback(result, token) {
        if (result === blackberry.push.PushService.SUCCESS) {
            // Success, so a token should be available
            // Subscribe with the Push Initiator using this
            // token (if your Push Initiator supports subscription)
            // so that you can push to this user using this token
        } else if (result ===
            blackberry.push.PushService.INTERNAL_ERROR) {
            // Retry the createChannel up to a certain number of
            // attempts and then display an error to the user
        } else if ... (handle all the error codes possible for
                       createChannel - see the error constants
                       in this PushService class)
    }
</script>
            

destroyChannel()

Destroys a push channel for the given application. A successful create must have been done and a channel must have been created using createChannel before calling this function. This function should be called in order for an application to stop receiving pushes. No pushes will be received after a destroyChannel call until a createChannel call is made after that.

Synopsis:

void PushService.destroyChannel(destroyChannelCallback)

Parameters:

destroyChannelCallback {Function}

The callback that is invoked when the result of the destroy channel operation is received.

result {Number}

The destroy channel operation result. See the constants provided to see what result codes apply for this operation.

Example:

<script type="text/javascript">

    pushService.destroyChannel(destroyChannelCallback);

    function destroyChannelCallback(result) {
        if (result === blackberry.push.PushService.INTERNAL_ERROR) {
            // Retry the destroyChannel up to a certain number
            // of attempts and then display an error to the user
        } else if ... (handle all the error codes possible for
                       destroyChannel - see the error constants
                       in this PushService class)
    }

</script>
            

extractPushPayload()

Extracts the PushPayload from the passed in invoke request. A successful create must have been done before calling this function.

Synopsis:

PushPayload extractPushPayload(invokeRequest)

Parameters:

invokeRequest {JSON}

The invoke request to parse.

Returns:

{PushPayload}

Returns the parsed out PushPayload object.

Throws:

{String}

An exception is thrown if the invokeRequest passed in is not valid and cannot be parsed.

Example:

<script type="text/javascript">

    try {
        var pushPayload =
            pushService.extractPushPayload(invokeRequest);

        // pushPayload.data is of type Blob
        // If the Blob is known to contain text,
        // then do something like this:
        blobToText(pushPayload.data, "UTF-8", textConversionCallback);

        // If the Blob is known to contain binary, then do
        // something like this to get an ArrayBuffer:
        // blobToArrayBuffer(pushPayload.data,
        //     binaryConversionCallback);
    } catch (err) {
        console.log("Was unable to parse the invoke request.");
        console.log(err);
    }

    function blobToText(blob, encoding, callback) {
        var reader = new FileReader();

        reader.onload = function(evt) {
            // No errors, get the result and call the callback
            callback(evt.target.result);
        };

        reader.onerror = function(evt) {
            console.log("Error converting Blob to string: " +
                evt.target.error);
        };

        reader.readAsText(blob, encoding);
    }

    function textConversionCallback(str) {
        console.log("Data received: " + str);
    }

    function blobToArrayBuffer(blob, callback) {
        var reader = new FileReader();

        reader.onload = function(evt) {
            // No errors, get the result and call the callback
            callback(evt.target.result);
        };

        reader.onerror = function(evt) {
            console.log("Error converting Blob to ArrayBuffer: " +
                evt.target.error);
        };

        reader.readAsArrayBuffer(blob);
    }

    function binaryConversionCallback(arrayBuffer) {
        // Process the ArrayBuffer containing
        // binary content as needed
    }

</script>
            

launchApplicationOnPush

Indicates whether or not the application should be launched (started up) if it is currently closed (not running) and a new push is received. The default system behaviour is to not launch the application. A successful create must have been done before calling this function. It is important to note that the shouldLaunch flag is only persisted once a channel has been created using the createChannel function. In other words, once the create channel function has been called the state of the shouldLaunch flag is persisted between application and device restarts. The flag is only removed once the destroy channel function is called. This flag can be toggled at any time using this function but, again, its value is only persisted once the create channel function has been called at least once for the lifetime of the application.

Synopsis:

void PushService.launchApplicationonPush(shouldLaunch, launchApplicationCallback)

Parameters:

shouldLaunch {Boolean}

True if the application should be launched on a new push; false if the application should not be launched when a new push comes in.

launchApplicationCallback {Function}

The callback that is invoked when the result of the launch application operation is received.

result {Number}

The launch application operation result. See the constants provided to see what result codes apply for this operation.

Example:

<script type="text/javascript">

    // Indicate that you want the application to launch on a new push
    pushService.launchApplicationOnPush(true,
        launchApplicationCallback);

    // To indicate that you do not want to launch on a new push,
    // either leave the default behaviour or call:
    // pushService.launchApplicationOnPush(false,
    //     launchApplicationCallback);

    function launchApplicationOnPush(result) {
       if (result === blackberry.push.PushService.INTERNAL_ERROR) {
         // Retry the launchApplicationOnPush up to a certain number
         // of attempts and then display an error to the user
       } else if ... (handle all the error codes possible for
                      launchApplicationOnPush - see the error
                      constants in this PushService class)
    }

</script>
            

CHANNEL_ALREADY_DESTROYED

Result error code when attempting to call destroy channel again after a successful destroy channel has already been done. Operations this error can occur on: destroyChannel (only if using public/BIS PPG). Recommended action: Most applications will typically want to just ignore this error code when it comes back.

Synopsis:

constant
Number PushService.CHANNEL_ALREADY_DESTROYED = 10004

CHANNEL_ALREADY_DESTROYED_BY_PROVIDER

Result error code when attempting to call destroy channel after a content provider has already done the destroying of the channel by unregistering a user. Operations this error can occur on: destroyChannel (only if using public/BIS PPG). Recommended action: Most applications will typically want to just ignore this error code when it comes back.

Synopsis:

constant
Number PushService.CHANNEL_ALREADY_DESTROYED_BY_PROVIDER = 10005

CHANNEL_SUSPENDED_BY_PROVIDER

Result error code when attempting to call destroy channel after a content provider has manually suspended a user. Operations this error can occur on: destroyChannel (only if using public/BIS PPG). Recommended action: Most applications will typically want to just ignore this error code when it comes back.

Synopsis:

constant
Number PushService.CHANNEL_SUSPENDED_BY_PROVIDER = 10012

CREATE_CHANNEL_NOT_DONE

Result error code when attempting to perform a destroy channel and a create channel has not been done beforehand. Operations this error can occur on: destroyChannel. Recommended action: This might mean a programming error in the application.

Synopsis:

constant
Number PushService.CREATE_CHANNEL_NOT_DONE = 10106

CREATE_CHANNEL_OPERATION

Constant associated with the createChannel operation. Compare this constant against pushTransportReadyCallback.lastFailedOperation to determine which failed operation should be tried again.

Synopsis:

constant
Number PushService.CREATE_CHANNEL_OPERATION = 1

CREATE_SESSION_NOT_DONE

Result error code when attempting to perform an operation and a create session has not been done beforehand. Operations this error can occur on: createChannel, destroyChannel, launchApplicationOnPush. Recommended action: This usually means a programming error in the application.

Synopsis:

constant
Number PushService.CREATE_SESSION_NOT_DONE = 10100

DESTROY_CHANNEL_OPERATION

Constant associated with the destroyChannel operation. Compare this constant against pushTransportReadyCallback.lastFailedOperation to determine which failed operation should be tried again.

Synopsis:

constant
Number PushService.DESTROY_CHANNEL_OPERATION = 2

EXPIRED_AUTHENTICATION_TOKEN_PROVIDED_TO_PPG

Result error code for when a create channel or destroy channel operation internally passes an expired authentication token to the PPG. Operations this error can occur on: createChannel, destroyChannel (only if using public/BIS PPG). Recommended action: Retrying the operation might correct the issue.

Synopsis:

constant
Number PushService.EXPIRED_AUTHENTICATION_TOKEN_PROVIDED_TO_PPG = 10008

INTERNAL_ERROR

Result error code for an internal error. Operations this error can occur on: create, createChannel, destroyChannel, launchApplicationOnPush. Recommended action: Retrying the operation might correct the issue.

Synopsis:

constant
Number PushService.INTERNAL_ERROR = 500

INVALID_AUTHENTICATION_TOKEN_PROVIDED_TO_PPG

This result error code should not typically be encountered. It would only occur if a create channel or destroy channel operation internally passes an invalid authentication token to the PPG. Operations this error can occur on: createChannel, destroyChannel (only if using public/BIS PPG). Recommended action: If this error occurs, it should be logged and reported to the BlackBerry support team.

Synopsis:

constant
Number PushService.INVALID_AUTHENTICATION_TOKEN_PROVIDED_TO_PPG = 10009

INVALID_DEVICE_PIN

Result error code for an invalid device PIN as determined by the PPG. Operations this error can occur on: createChannel, destroyChannel (only if using public/BIS PPG). Recommended action: Retrying the operation might correct the issue. The PIN is obtained under the covers by the public/BIS PPG. It very rarely has issues obtaining the device PIN, so a retry might fix this.

Synopsis:

constant
Number PushService.INVALID_DEVICE_PIN = 10001

INVALID_OS_VERSION_OR_DEVICE_MODEL_NUMBER

Result error code for when a device attempting to do a create channel has an invalid operating system version number or an invalid device model number. Operations this error can occur on: createChannel (only if using public/BIS PPG). Recommended action: Retrying the operation is not recommended since this is an unrecoverable error that is out of control of the application. It might make sense to communicate this issue up to the user.

Synopsis:

constant
Number PushService.INVALID_OS_VERSION_OR_DEVICE_MODEL_NUMBER = 10011

INVALID_PPG_SUBSCRIBER_STATE

This result error code should not typically be encountered. It would only occur if a create or destroy channel operation internally causes the state of a subscriber on the PPG to be in an invalid state. Operations this error can occur on: createChannel, destroyChannel (only if using public/BIS PPG). Recommended action: If this error occurs, it should be logged and reported to the BlackBerry support team.

Synopsis:

constant
Number PushService.INVALID_PPG_SUBSCRIBER_STATE = 10006

INVALID_PPG_URL

Result error code when an invalid PPG URL was specified. Operations this error can occur on: createChannel, destroyChannel (only if using public/BIS PPG). Recommended action: Specifying a valid value for options.ppgUrl in the static create function and retrying might correct the issue.

Synopsis:

constant
Number PushService.INVALID_PPG_URL = 10114

INVALID_PROVIDER_APPLICATION_ID

Result error code for an invalid provider application ID. Either an invalid one was specified or none at all. Operations this error can occur on: create, createChannel, destroyChannel (only if using public/BIS PPG). Recommended action: Specifying a valid value for options.appId in the static create function and retrying might correct the issue.

Synopsis:

constant
Number PushService.INVALID_PROVIDER_APPLICATION_ID = 10002

MISSING_INVOKE_TARGET_ID

Result error code when no invoke target ID is specified on a create operation. Operations this error can occur on: create. Recommended action: Specifying a value for options.invokeTargetId in the static create function and retrying might correct the issue.

Synopsis:

constant
Number PushService.MISSING_INVOKE_TARGET_ID = 10111

MISSING_PORT_FROM_PPG

Result error code as a result of an issue on a create channel operation obtaining a port from the PPG. Operations this error can occur on: createChannel. Recommended action: Retrying the operation might correct the issue.

Synopsis:

constant
Number PushService.MISSING_PORT_FROM_PPG = 10107

MISSING_PPG_URL

Result error code when attempting to perform a create channel and a PPG URL was missing. Operations this error can occur on: createChannel (only if using public/BIS PPG). Recommended action: Specifying a value for options.ppgUrl in the static create function and retrying might correct the issue.

Synopsis:

constant
Number PushService.MISSING_PPG_URL = 10102

MISSING_SUBSCRIPTION_RETURN_CODE_FROM_PPG

Result error code as a result of an issue on a create channel operation obtaining a subscription return code from the PPG. Operations this error can occur on: createChannel (only if using public/BIS PPG). Recommended action: Retrying the operation might correct the issue.

Synopsis:

constant
Number PushService.MISSING_SUBSCRIPTION_RETURN_CODE_FROM_PPG = 10108

OPERATION_NOT_SUPPORTED

Result error code when a certain operation is currently not supported. Recommended action: This operation might not yet be implemented and so should not be performed.

Synopsis:

constant
Number PushService.OPERATION_NOT_SUPPORTED = 10105

PPG_SERVER_ERROR

Result error code when the PPG returns a server error. Operations this error can occur on: createChannel, destroyChannel (only if using public/BIS PPG). Recommended action: Wait until pushTransportReadyCallback (one of the arguments in the static create function) is called before retrying.

Synopsis:

constant
Number PushService.PPG_SERVER_ERROR = 10110

PPG_SUBSCRIBER_LIMIT_REACHED

Result error code for when too many devices have already performed a create channel for the provider application ID. (A create channel will effectively register a user with the PPG for public/BIS). Operations this error can occur on: createChannel (only if using public/BIS PPG). Recommended action: No action can be taken by the application for this error, but it should somehow be communicated back to the content provider and then to BlackBerry to try to increase the allowed subscription limit.

Synopsis:

constant
Number PushService.PPG_SUBSCRIBER_LIMIT_REACHED = 10010

PPG_SUBSCRIBER_NOT_FOUND

Result error code for when a destroy channel operation fails because the subscriber could not be found on the PPG's end. Operations this error can occur on: destroyChannel (only if using public/BIS PPG). Recommended action: This error can most likely be ignored since if the subscriber could not be found on the PPG's end, then destroying the channel will have no effect anyway (it is as if they were never registered with the PPG using create channel).

Synopsis:

constant
Number PushService.PPG_SUBSCRIBER_NOT_FOUND = 10007

PUSH_TRANSPORT_UNAVAILABLE

Result error code when a create channel or destroy channel operation has failed due to network issues or the push transport being down. Operations this error can occur on: createChannel, destroyChannel (only if using public/BIS PPG). Recommended action: Wait until pushTransportReadyCallback (one of the arguments in the static create function) is called before retrying. This error can also occur when the user's wireless connection (e.g. Wi-Fi, Mobile Network) is off or temporarily down, so it might make sense to communicate this issue up to the user to double check their wireless connection.

Synopsis:

constant
Number PushService.PUSH_TRANSPORT_UNAVAILABLE = 10103

SESSION_ALREADY_EXISTS

Result error code when an underlying session already exists. Operations this error can occur on: create. Recommended action: Check options.appId and options.invokeTargetId in the static create function to ensure that they are valid and unique to your application.

Synopsis:

constant
Number PushService.SESSION_ALREADY_EXISTS = 10112

SUCCESS

Result code for an operation that was performed successfully. Operations this code applies to: create, createChannel, destroyChannel, launchApplicationOnPush.

Synopsis:

constant
Number PushService.SUCCESS : 0

Last modified: 2014-10-09



Got questions about leaving a comment? Get answers from our Disqus FAQ.

comments powered by Disqus