net.rim.blackberry.push.PushService

PushService

Methods | Events | Examples


Packagenet.rim.blackberry.push
Classpublic class PushService
InheritancePushService Inheritance flash.events.EventDispatcher

Main service class for performing push-related operations. Only one instance of this class should be created for your application.

Note that, to use push if you are writing a consumer application for the general public, you must specify the following permission tag in your bar-descriptor.xml file:

For a great sample app that demonstrates how to use the push APIs, see Push Receiver.

There is also a very valuable developer guide for the Push Receiver sample app that you can find here.

PushService provides APIs that permit BlackBerry applications to create and destroy push channels in order to start and stop receiving push messages.

Push messages are initiated via a content provider's server-side application (known as the Push Initiator) and sent through the Push Proxy Gateway (PPG) to a Push Service agent running on the device. The Push Service agent will broker outgoing and incoming requests to and from the PPG and your application.

If you are writing a consumer application for the general public, you will make use of the public/BlackBerry Internet Service (BIS) PPG. If you are writing an enterprise application, then you will make use of an enterprise/Blackberry Enterprise Server (BES) PPG instead.

Most function calls will be identical between consumer and enterprise applications. There are two key differences:

  • When creating a PushService instance, for a consumer application, you will need to specify a provider application ID. For an enterprise application, you have the choice of not specifying a provider application ID.
  • When calling the createChannel function, for a consumer application, you will need to specify a PPG URL. For an enterprise application, no PPG URL should be specified.

In order for the application on the device to communicate with the Push Service agent, it must first create a session. The createSession API dispatches a PushServiceEvent of type CREATE_SESSION_SUCCESS on success, or dispatches a PushServiceErrorEvent of type CREATE_SESSION_ERROR on failure.

If the application wishes to be launched (started up) when it is closed and a new push notification comes in, it can use the registerToLaunch API. If the application has registered to launch and it wishes to unregister, it can use the unregisterFromLaunch API. It is highly recommended that these "launch" functions be called in the event handler for a successful create session operation.

Once a session with the Push Service agent has been successfully created, a channel must be created between the PPG and the Push Service agent. A channel enables a content provider to push messages to the application on the device. A channel can be created by using the createChannel API. Unlike a session, once a channel is created it will survive application restarts and therefore does not need to be called on every application start up. The createChannel API dispatches a CreateChannelSuccessEvent on success, or dispatches a PushServiceErrorEvent of type CREATE_CHANNEL_ERROR on failure.

When a channel is created successfully, the CreateChannelSuccessEvent will return a token from the PPG. 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.

When creating a channel fails and you receive a PushServiceErrorEvent.PUSH_TRANSPORT_UNAVAILABLE or a PushServiceErrorEvent.PPG_SERVER_ERROR error code, then you will receive a PushTransportReadyEvent event when the network/push transport/PPG is back up and available again.

Once the channel is created, push messages initiated by the content provider will be dispatched to the application via an InvokeEvent. The invocation request will have an action of InvokeAction.PUSH. The invocation request can then be converted into a PushPayload object using the supplied extractPushPayload function.

The PushPayload object will contain a Boolean (isAckRequired) indicating if the Push Initiator requested that the application acknowledge receipt of the push message. If the Boolean is set to true, the acceptPush or rejectPush API should be called in a timely manner; otherwise the push will be considered as a failed delivery.

If the application no longer wishes to receive push messages, temporarily or permanently, it can use the destroyChannel API. This will destroy the channel from the PPG to the application on the device. Any further push requests by the content provider will by rejected by the PPG. It is recommended that the application also notify the content provider server-side application that it no longer wishes to receive push messages to prevent the content provider from unnecessarily sending push requests to the PPG.

A PushServiceEvent of type SIM_CHANGE is dispatched to the application if the SIM card on the device has changed (if the device supports a SIM card). When the Push Service agent detects a SIM change, it will automatically destroy the channel 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 content provider's server-side application and then re-create the channel using createChannel. This event is only dispatched once the application has been started and created a session after a SIM card change.

When any of the create session, create channel, destroy channel, register to launch, or unregister from launch operations fails with a PushServiceErrorEvent.PUSH_SERVICE_CONNECTION_CLOSED error code, then you will receive a PushServiceConnectionReadyEvent event when the Push Service connection is back up and available again.



Class information:
BlackBerry 10 Version: 10.0.0
Found in:  BlackBerryPushService.ane

View the examples



Public Methods

 MethodDefined By
  
PushService(invokeTargetID:String, providerApplicationID:String = null)
Constructs a PushService object in order to perform push-related operations.
PushService
  
acceptPush(payloadId:String):void
Sends an acknowledgement to the PPG indicating that the push has been accepted.
PushService
  
createChannel(ppgUrl:String = null):void
Creates a push channel for the given application.
PushService
  
Creates a push session for the given application with the Push Service agent.
PushService
  
Destroys a push channel for the given application.
PushService
  
dispose():void
Disposes of all the push-related system resources.
PushService
  
Extracts a PushPayload object from the supplied InvokeRequest.
PushService
  
isSupported():Boolean
[static] Returns whether the Push Service is supported on the platform the application is currently running on.
PushService
  
Registers the application to be launched when a new push notification is received.
PushService
  
rejectPush(payloadId:String):void
Sends an acknowledgement to the PPG indicating that the push has been rejected.
PushService
  
Unregisters the application from being launched when a new push notification is received.
PushService

Events

 Event Summary Defined By
  Dispatched when a create channel operation has failed.PushService
  Dispatched when a create channel operation has succeeded.PushService
  Dispatched when a create session operation has failed.PushService
  Dispatched when a create session operation has succeeded.PushService
  Dispatched when a destroy channel operation has failed.PushService
  Dispatched when a destroy channel operation has succeeded.PushService
  Dispatched when the connection to the Push Service is back up and ready again after a create session, create channel, destroy channel, register to launch or unregister from launch operation previously failed with the PushServiceErrorEvent.PUSH_SERVICE_CONNECTION_CLOSED error code.PushService
  Dispatched when the network/push transport/PPG is back up and ready again after a create channel or destroy channel operation previously failed with either the PushServiceErrorEvent.PUSH_TRANSPORT_UNAVAILABLE or the PushServiceErrorEvent.PPG_SERVER_ERROR error code.PushService
  Dispatched when a register to launch operation has failed.PushService
  Dispatched when a register to launch operation has succeeded.PushService
  Dispatched when a SIM card change has occurred.PushService
  Dispatched when an unregister from launch operation has failed.PushService
  Dispatched when an unregister from launch operation has succeeded.PushService

Constructor Detail

PushService()


public function PushService(invokeTargetID:String, providerApplicationID:String = null)

Constructs a PushService object in order to perform push-related operations.

Parameters

invokeTargetID:String — Your application's unique invoke target ID for push, as set in your bar-descriptor.xml file. It relates to when a new push notification is received and the application needs to be invoked.
providerApplicationID:String (default = null) — 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 providerApplicationID (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).


Throws

ArgumentError — if no invokeTargetID is specified or if invokeTargetID or providerApplicationID contains invalid characters
InitializationError — if the PushService could not be created due to an unrecoverable internal error trying to allocate system resources or if a PushService instance already exists with a different invokeTargetID value or providerApplicationID value

Method Detail

acceptPush()


public function acceptPush(payloadId:String):void

Sends an acknowledgement to the PPG indicating that the push has been accepted. It is up to the application to determine whether to accept or reject a push message based on its own business rules. It is strongly recommended to accept or reject the push message as soon as possible otherwise the push message will automatically be considered rejected.

Use the PushPayload.isAckRequired property to determine whether or not calling acceptPush or rejectPush is required.

Parameters

payloadId:String — the unique identifier of the push. It will match the PushPayload.id property.


Throws

IllegalOperationError — if attempting to use this instance of PushService after calling the dispose API

createChannel()


public function createChannel(ppgUrl:String = null):void

Creates a push channel for the given application. Unlike a session, once a channel is created it will survive application restarts and therefore does not need to be called on every application start up.

A session must have been created using createSession before creating the channel.

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.

If writing a consumer application, it is possible that the service might destroy a channel under certain circumstances. Therefore, it might be advisable to periodicially re-create the channel (e.g. once a month). This is not a concern for an enterprise application.

Parameters

ppgUrl:String (default = null) — the PPG URL. 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.


Throws

IllegalOperationError — if attempting to use this instance of PushService after calling the dispose API

createSession()


public function createSession():void

Creates a push session for the given application with the Push Service agent.

This function should be called every time an application starts up. That is because a current, active session is required in order to receive pushes.


Throws

IllegalOperationError — if attempting to use this instance of PushService after calling the dispose API

destroyChannel()


public function destroyChannel():void

Destroys a push channel for the given application.

A session and a channel must have been created using createSession and createChannel before destroying the channel.

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.


Throws

IllegalOperationError — if attempting to use this instance of PushService after calling the dispose API

dispose()


public function dispose():void

Disposes of all the push-related system resources. Once dispose has been called, the PushService object it is called on will be in an invalid state and a new instance must be created if the application wishes to use PushService again.


Throws

IllegalOperationError — if attempting to use this instance of PushService after calling the dispose API has already been called previously

extractPushPayload()


public function extractPushPayload(invokeRequest:InvokeRequest):PushPayload

Extracts a PushPayload object from the supplied InvokeRequest. The InvokeRequest must be of type InvokeAction.PUSH

Parameters

invokeRequest:InvokeRequest — an invoke request received from an InvokeEvent.INVOKE event

Returns

PushPayload — the extracted PushPayload object or null if the push payload could not be extracted

Throws

ArgumentError — if the InvokeRequest has the wrong action type or is not valid and cannot be parsed
IllegalOperationError — if attempting to use this instance of PushService after calling the dispose API

isSupported()


public static function isSupported():Boolean

Returns whether the Push Service is supported on the platform the application is currently running on.

Returns

Boolean — A value of true means the Push Service is supported for the current platform; a value of false means that the Push Service is not supported and an instance of PushService should not be constructed for the current platform.

registerToLaunch()


public function registerToLaunch():void

Registers the application to be launched when a new push notification is received. If not registered, the application will not start up if it is closed and a new push notification is received.

A session must have been created using createSession before registering to launch.

It is highly recommended that a register to launch be performed right after a successful create session. That is, in the event handler for an event of type PushServiceEvent.CREATE_SESSION_SUCCESS.


Throws

IllegalOperationError — if attempting to use this instance of PushService after calling the dispose API

rejectPush()


public function rejectPush(payloadId:String):void

Sends an acknowledgement to the PPG indicating that the push has been rejected. It is up to the application to determine whether to accept or reject a push message based on its own business rules. It is strongly recommended to accept or reject the push message as soon as possible otherwise the push message will automatically be considered rejected.

Use the PushPayload.isAckRequired property to determine whether or not calling acceptPush or rejectPush is required.

Parameters

payloadId:String — the unique identifier of the push. It will match the PushPayload.id property.


Throws

IllegalOperationError — if attempting to use this instance of PushService after calling the dispose API

unregisterFromLaunch()


public function unregisterFromLaunch():void

Unregisters the application from being launched when a new push notification is received. If registered, the application will no longer start up if it is closed and a new push notification is received. If not registered, this call has no effect.

A session must have been created using createSession before unregistering from launch.

It is highly recommended that an unregister from launch be performed right after a successful create session. That is, in the event handler for an event of type PushServiceEvent.CREATE_SESSION_SUCCESS.


Throws

IllegalOperationError — if attempting to use this instance of PushService after calling the dispose API

Event Detail

createChannelError


Event Object Type: net.rim.blackberry.events.PushServiceErrorEvent

Dispatched when a create channel operation has failed.

createChannelSuccess


Event Object Type: net.rim.blackberry.events.CreateChannelSuccessEvent

Dispatched when a create channel operation has succeeded.

createSessionError


Event Object Type: net.rim.blackberry.events.PushServiceErrorEvent

Dispatched when a create session operation has failed.

createSessionSuccess


Event Object Type: net.rim.blackberry.events.PushServiceEvent

Dispatched when a create session operation has succeeded.

destroyChannelError


Event Object Type: net.rim.blackberry.events.PushServiceErrorEvent

Dispatched when a destroy channel operation has failed.

destroyChannelSuccess


Event Object Type: net.rim.blackberry.events.PushServiceEvent

Dispatched when a destroy channel operation has succeeded.

pushServiceConnectionReady


Event Object Type: net.rim.blackberry.events.PushServiceConnectionReadyEvent

Dispatched when the connection to the Push Service is back up and ready again after a create session, create channel, destroy channel, register to launch or unregister from launch operation previously failed with the PushServiceErrorEvent.PUSH_SERVICE_CONNECTION_CLOSED error code. This event will indicate the last operation that was performed that failed (either create session, create channel, destroy channel, register to launch or unregister from launch) so that it can be tried again.

pushTransportReady


Event Object Type: net.rim.blackberry.events.PushTransportReadyEvent

Dispatched when the network/push transport/PPG is back up and ready again after a create channel or destroy channel operation previously failed with either the PushServiceErrorEvent.PUSH_TRANSPORT_UNAVAILABLE or the PushServiceErrorEvent.PPG_SERVER_ERROR error code. This event will indicate the last operation that was performed that failed (either create channel or destroy channel) so that it can be tried again.

registerToLaunchError


Event Object Type: net.rim.blackberry.events.PushServiceErrorEvent

Dispatched when a register to launch operation has failed.

registerToLaunchSuccess


Event Object Type: net.rim.blackberry.events.PushServiceEvent

Dispatched when a register to launch operation has succeeded.

simChange


Event Object Type: net.rim.blackberry.events.PushServiceEvent

Dispatched when a SIM card change has occurred. This event is only dispatched once the application has been started and created a session after a SIM card change.

unregisterFromLaunchError


Event Object Type: net.rim.blackberry.events.PushServiceErrorEvent

Dispatched when an unregister from launch operation has failed.

unregisterFromLaunchSuccess


Event Object Type: net.rim.blackberry.events.PushServiceEvent

Dispatched when an unregister from launch operation has succeeded.

Examples

     
     import net.rim.blackberry.events.CreateChannelSuccessEvent;
     import net.rim.blackberry.events.PushServiceConnectionReadyEvent;
     import net.rim.blackberry.events.PushServiceErrorEvent;
     import net.rim.blackberry.events.PushServiceEvent;
     import net.rim.blackberry.events.PushTransportReadyEvent;
     import net.rim.blackberry.push.PushService;
     
     import qnx.events.InvokeEvent;
     import qnx.invoke.InvokeAction;
     import qnx.invoke.InvokeManager;
     import qnx.invoke.InvokeRequest;
      
     private var pushService:PushService;
     
     public function init():void 
     {
         // Listen for invocation events
         InvokeManager.invokeManager.addEventListener(
             InvokeEvent.INVOKE, invokeHandler);
     
         try {
             // "invokeTargetId" matches your application's invoke 
             // target ID that gets invoked when a new push 
             // notification comes in. Invocation targets need to 
             // be configured in your bar-descriptor.xml file.
          
             // For a consumer application, "providerAppId" matches
             // the provider application ID of your push application 
             // that you received after registering to use the 
             // public/BIS PPG push service
             pushService = new PushService(invokeTargetId, 
                 providerAppId);
              
             // For an enterprise application, you have the choice
             // of calling: 
             // pushService = new PushService(invokeTargetId);
             // in which case a unique application ID will be assigned 
             // to your enterprise application under the covers.
             // Or, you can specify your own unique application ID if 
             // you need the application ID for other purposes in your 
             // code such as subscribing with the Push Initiator:
             // pushService = new PushService(invokeTargetId, 
             //     enterpriseAppId);
         } catch (error:ArgumentError) {    
             // If no invokeTargetId is specified or invokeTargetId, 
             // providerAppId, or enterpriseAppId contains invalid 
             // characters             
             trace("ArgumentError while creating push service: " +
                 error.message + "\r" + error.getStackTrace());
          
             throw error;
         } catch (error:InitializationError) {
             // If PushService could not be created
             trace("InitializationError while creating push service: " +
                 error.message + "\r" + error.getStackTrace());
     
             throw error;
         }  
     
         // Add event listeners for the various push-related events
         pushService.addEventListener(
             PushServiceErrorEvent.CREATE_SESSION_ERROR, 
             createSessionErrorHandler);
         pushService.addEventListener(
             PushServiceEvent.CREATE_SESSION_SUCCESS, 
             createSessionSuccessHandler); 
         pushService.addEventListener(
             PushServiceErrorEvent.CREATE_CHANNEL_ERROR, 
             createChannelErrorHandler);
         pushService.addEventListener(
             CreateChannelSuccessEvent.CREATE_CHANNEL_SUCCESS, 
             createChannelSuccessHandler);
         pushService.addEventListener(
             PushServiceErrorEvent.DESTROY_CHANNEL_ERROR, 
             destroyChannelErrorHandler);
         pushService.addEventListener(
             PushServiceEvent.DESTROY_CHANNEL_SUCCESS, 
             destroySuccessHandler);
         pushService.addEventListener(PushServiceEvent.SIM_CHANGE, 
             simChangeHandler);  
         pushService.addEventListener(
             PushTransportReadyEvent.PUSH_TRANSPORT_READY, 
             pushTransportReadyHandler);
         pushService.addEventListener(
             PushServiceErrorEvent.REGISTER_TO_LAUNCH_ERROR, 
             registerToLaunchErrorHandler);
         pushService.addEventListener(
             PushServiceEvent.REGISTER_TO_LAUNCH_SUCCESS, 
             registerToLaunchSuccessHandler);
         pushService.addEventListener(
             PushServiceErrorEvent.UNREGISTER_FROM_LAUNCH_ERROR, 
             unregisterFromLaunchErrorHandler);
         pushService.addEventListener(
             PushServiceEvent.UNREGISTER_FROM_LAUNCH_SUCCESS, 
             unregisterFromLaunchSuccessHandler);
         pushService.addEventListener(
             PushServiceConnectionReadyEvent.
             PUSH_SERVICE_CONNECTION_READY,
             pushServiceConnectionReadyHandler);
     }
     
     public function createSession():void
     {
         pushService.createSession();
     }
     
     public function createChannel():void 
     {
         // For a consumer application, a PPG URL must be specified.
         // We will specify the PPG URL of the public/BIS PPG eval 
         // environment here as an example. 
         // Note: Make sure http (not https) is used and you 
         // replace {cpid} with your content provider ID!
         pushService.createChannel(
             "http://cp{cpid}.pushapi.eval.blackberry.com");
     
         // If pushing to an enterprise PPG, you would instead call:
         // pushService.createChannel();
     }
     
     public function destroyChannel():void 
     {
         pushService.destroyChannel();
     }
     
     public function registerToLaunch():void
     {
         pushService.registerToLaunch();
     }
     
     public function unregisterFromLaunch():void
     {
         pushService.unregisterFromLaunch();
     }
     
     private function invokeHandler(event:InvokeEvent):void 
     {
         var invokeManager:InvokeManager = e.target as InvokeManager; 
         var invokeRequest:InvokeRequest = invokeManager.startupRequest;
     
         if (invokeRequest.action == InvokeAction.PUSH) {
             try {
                  var pushPayload:PushPayload = 
                      pushService.extractPushPayload(
                          invokeManager.startupRequest);
     
                  pushNotificationHandler(pushPayload);
             } catch (error:ArgumentError) {    
                  // If invoke request is invalid or cannot be parsed             
                  trace("ArgumentError while extracting the push " +
                      "payload: " + error.message + "\r" + 
                      error.getStackTrace());
     
                     throw error;
            }             
         } else if (invokeRequest.action == ...
             // Handle other types of invocations that 
             // are not push specific
         }
     }
     
     private function pushNotificationHandler(push:PushPayload):void 
     {
         var contentTypeHeaderVal:String = 
             push.getHeader("Content-Type");
     
         trace("Newly received push Base64 encoded bytes: " + 
             Base64.encode(push.data));
     
         trace("Value of the Content-Type header: " + 
             contentTypeHeaderVal);
     
         // If push.isAckRequired() is true, then call acceptPush 
         // or rejectPush in a timely manner
     }
     
     private function createSessionErrorHandler(
         event:PushServiceErrorEvent):void 
     {
         trace("Create session failed with error code: " + 
             event.errorID + " and description: " + event.text);
         // Try again later
     }
     
     private function createSessionSuccessHandler(
         event:PushServiceEvent):void 
     {
         trace("Create session succeeded");
         // Now, register to launch (if desired)
         // Or, unregister from launch (if already registered 
         // to launch and wanting to unregister)
     }
      
     private function registerToLaunchErrorHandler(
         event:PushServiceErrorEvent):void
     {
         trace("Register to launch failed with error code: " +
             event.errorID + " and description: " + event.text);
     }
     
     private function registerToLaunchSuccessHandler(
         event:PushServiceEvent):void
     {
         trace("Register to launch succeeded");
         // Now, create a channel
     }
     
     private function unregisterFromLaunchErrorHandler(
         event:PushServiceErrorEvent):void
     {
         trace("Unregister from launch failed with error code: " +
             event.errorID + " and description: " + event.text);
     }
     
     private function unregisterFromLaunchSuccessHandler(
         event:PushServiceEvent):void
     {
         trace("Unregister from launch succeeded");
         // Now, create a channel
     } 
     
     private function createChannelErrorHandler(
         event:PushServiceErrorEvent):void 
     {
         trace("Create channel failed with error code: " +
             event.errorID + " and description: " + event.text);
     }
     
     private function createChannelSuccessHandler(
         event:CreateChannelSuccessEvent):void
      {
         trace("Create channel succeeded and returned token: " +
             event.token);
         // This token needs to be communicated back to the content
         // provider's server-side application (the Push Initiator)
     }
     
     private function destroyChannelErrorHandler(
         event:PushServiceErrorEvent):void 
     {
         trace("Destroy channel failed with error code: " +
             event.errorID + " and description: " + event.text);
     }
     
     private function destroySuccessHandler(event:PushServiceEvent):void 
     {
         trace("Destroy channel succeeded");
     }
      
     private function simChangeHandler(event:PushServiceEvent):void 
     {
         trace("SIM change detected");
         // Re-authenticate the user and re-create the channel
     }
     
     private function pushTransportReadyHandler(
         event:PushTransportReadyEvent):void
     {
         trace("Push transport ready");
         // Look at event.lastFailedOperation and try a create 
         // channel or destroy channel again
     }
     
     private function pushServiceConnectionReadyHandler(
         event:PushServiceConnectionReadyEvent):void
     {
         trace("Push Service connection ready");
         // Look at event.lastFailedOperation and try a create 
         // session, create channel, register to launch,
         // or unregister from launch again
     }
     




comments powered by Disqus