# Activity Manager Data Types

Data type | Description | Ref'd by | APIs
--- | --- | --- | ---
Activity | Activity object. |  | create
ActivityEvent | Activity event notification object sent to Activity subscribers. |  |
Activity Manager Callback Property | Additional object passed to an Activity's callback method. |  |
Callbacks | Callback method object. | Activity | complete
Parent | Activity parent's app ID or service ID. | Activity |
Requirements | Prerequisites that must be met before an Activity can run. | Activity | complete
Schedule | Activity's time-based requirements. | Activity | complete
State | Activity state string. | Activity ActivityEvent | monitor
Triggers | Event that must occur before Activity can run. | Activity | complete
Type | Details how the Activity is handled— foreground, background, pauseable, cancelable, etc. | Activity |

## Activity

Represents everything about an Activity—name, type, state, requirements, schedule, trigger, callback, id, creator, adopters, processes, flows, and associations.

### Schema

>     {
>       //** The following are Activity creator specified attributes

>       "name"         :  string,
>       "description"  :  string,
>       "type"         :  <a href="#Type">Type</a>,
>       "requirements" :  <a href="#Requirements">Requirements</a>,
>       "schedule"     :  <a href="#Schedule">Schedule</a>,
>       "trigger"      :  <a href="#Triggers">Trigger</a>,
>       "callback"     :  <a href="#Callbacks">Callback</a>,

>       //** The following are AM maintained read-only attributes.
>       "metadata"     : any object,
>       "activityId"   : int,
>       "creator"      : <a href="#Parent">Parent</a>,
>       "parent"       : <a href="#Parent">Parent</a>,
>       "adopters"     : <a href="#Parent">Parent</a> array,
>       "state"        : <a href="#State">State</a>,
>       "focused"      : boolean
>     }

### Elements

Element | Required | Type | Description
--- | --- | --- | ---
name | Yes | string | Activity name. Must be unique for creator. Applies to both persistent and non-persistent Activities. The create call will fail if this field is not unique unless the "replace" field is true.
description | Yes | string | Activity description.
type | Yes | Type | Indicates how the Activity is handled. Principally, it is used to denote the Activity as either foreground or background, and whether it can be paused or cancelled.
requirements | No | Requirements | Conditions that must be met for Activity to run.
schedule | No | Schedule | Time-based requirements for Activity.
trigger | No | Trigger | Event that must occur for Acitivity to run.
callback | No | Callback | Call to invoke when Activity runs.
metadata | No | any object | Opaque object the Activity Manager stores and returns in the callback parameters. Can be retrieved with the list or getDetails method calls.
activityId | No | int | Activity ID.
creator | No | Parent | Activity creator.
parent | No | Parent | Activity parent.
adopters | No | Parent array | Activity adopters.
state | No | State | Activity state.
focused | No | boolean | Does Activity have focus flag.

Example

See create method for examples of using an Activity object.

## ActivityEvent

Activity events are sent to all subscribed listeners. An event includes the event name and the Activity's ID and state. Apps or services can subscribe to an Activity through either the create, adopt, or monitor methods.

### Schema

>     {
>       "activityId" : int,
>       "event"      : string,
>       "state"      : <a href="#State">State</a>
>     }

### Elements

Element | Required | Type | Description
--- | --- | --- | ---
activityId | Yes | int | Activity ID.
event | Yes | string | Possible events listed in table below.
state | Yes | State object. | Activity state - stopped, running, etc.

### Possible Events

Event | Description
--- | ---
`start` | The Activity has permission to run and should proceed.
`stop` | The Activity should exit in an orderly fashion as soon as practically possible.
`pause` | The Activity should pause and wait to return to the run state.
`cancel` | The Activity is cancelled immediately.
`orphan` | Sent to a subscribed potential Activity parent (who registered with the adopt method) when the Activity's current parent closed or released the Activity.
`adopted` | After an Activity has been successfully adopted, this is sent to the Activity's previous parent in case they wish to unsubscribe.
`focused` | The Activity is now the focused foreground Activity.
`unfocused` | The Activity is no longer the focused foreground Activity.

Example

>     {
>       "activityId" : 629,
>       "event"      : "stop",
>       "state"      : {"stopping"}
>     }

## Activity Manager Callback Property

The Activity Manager inserts an additional property to the parameters specified for an Activity's callback method — "$activity". This property contains additional trigger information.

### Schema

>     {
>       "activityId"   : int,
>       "name"         : string,
>       "creator"      : string,
>       "requirements" : any,
>       "trigger"      : string,
>       "metadata"     : any,
>       "serial"       : string
>     }

### Elements

Element | Required | Type | Description
--- | --- | --- | ---
activityId | Yes | int | Acitivity ID.
name | No | string | Activity name.
creator | No | string | ID of app or service that created Activity.
requirements | No | any | Map of requirements fields to actual values that met the requirements specified. For example, if `minimumbandwidth` is specified, then a `minimumbandwidth` field is passed back indicating how much bandwidth there actually was when the requirement was met.
trigger | No | string | Reply that caused the Trigger to fire (if appropriate)
metadata | No | any | Opaque object passed by caller to the create method.
serial | No | string | Random number assigned to each callback invocation.

Example with Requirements

Users may want to know the value that fulfilled a requirement, not just that the requirement was met. To satisfy this, the AM passes back information in the `requirements` field. The `requirements` property has the same name as the property used to specify the requirement. For example, if `requirements` specified that the battery charge percentage had to be at least 50:

       "requirements"  : {
                           "battery" : 50
                         }

Then, the information passed back to the callback would have a property of the same name indicating the current percentage:

        "$activity" : {
           "activityId" : 3,
           "requirements" : {
              "battery" : 75  // Requirement was met with this value
           }
        }

## Callbacks

Callbacks allow a service to stop running and consuming resources while it waits for an Activity to start at a set time or for a trigger to fire. When the Activity begins, the callback is invoked and the service can resume. A callback specification consists of a method and any arguments. In addition to arguments, the callback is passed Activity Manager Callback Property information. Activities with a callback should be started immediately. The Activity Manager invokes the callback when the prerequisites are met and, in the case of a background/non-immediate Activity, it is cleared to run.

### Schema

>     {
>       "method" : string,
>       "params" : any
>     }

### Elements

Element | Required | Type | Description
--- | --- | --- | ---
method | Yes | string | Callback URI.
params | No | any | Any parameters to pass to the callback.

Example

>     {
>       "method": "palm://com.palm.connectionmanager/getStatus",
>       "params": {"subscribe":true}
>     }

## Parent

The Parent (or potential parent) of an Activity specified as an app ID or service ID. The Activity Manager automatically obtains this value when the app or service invokes the create or adopt method.

### Schema

>     {
>       "appId" : "string" | "serviceId" : "string"  // Either or
>     }

### Elements

Element | Required | Type | Description
--- | --- | --- | ---
appId | No | string | Application ID. Either this or serviceId must be specified.
serviceId | No | string | Service ID. Either this or appId must be specified.

Example

>     {
>       "appId": "com.palm.google"
>     }

## Requirements

Conditions that must be met (i.e., telephony subsystem or network availability) before an Activity can run. A foreground Activity can run as soon as its conditions are met and, if a Trigger is specified, the Trigger has fired. Once a background Activity's requirements are met it can be ready to run but not actually running until needed resources are available and other running Activities have completed.

In addition, no background Activity can run while the system is booting. The Activity Manager can stop launching background Activities, or pause or cancel currently running background Activities, if device temperature exceeds a critical threshold. Other conditions also determine if background Activities can run.

When the Activity runs, the Activity Manager (for some particular requirements where this makes sense) can inform the service exactly how its requirements were met. This way, the service does not have to immediately query other services to determine how to proceed when starting Activity work. For example, for the "internet" requirement, the Activity Manager returns what interfaces are available and what addresses they have assigned to the service in the service's callback. This avoids having the service query the Connection Manager to bind to a particular interface.

Requirements Update Notification

The Activity Manager can generate "update" events when an Activity's requirement changes. To enable this, set the "detailedEvents" flag to true (in addition to setting "subscribe" to true) when calling create, adopt, or monitor. All events generated to a subscription contain an $activity property like the one initially provided to the Activity's callback method which contains the current state of the Activity's requirements in the "requirements" sub-property.

Note: All fields are optional.

### Schema

>     {
>       "telephony" : boolean,
>       "minimumbandwidth" : int,
>       "wifi"      : boolean,
>       "wan"       : boolean,
>       "idle"      : int,
>       "blanked"   : int,
>       "battery"   : int,
>       "charging"  : boolean,
>       "docked"    : boolean
>     }

Element | Required | Type | Description
--- | --- | --- | ---
telephony | No | boolean | Is telephony available flag.
minimumbandwidth | No | int | Minimum bandwidth in kilobytes to run.
wifi | No | boolean | Is WiFi available flag.
wan | No | boolean | Is Wide-Area Network available flag.
idle | No | int | Idle time in seconds. Not currently implemented.
blanked | No | int | Time since screen blanked, in seconds. Not currently implemented.
battery | No | int (0-100) | Minimum battery charged percentage to run, 0-100.
charging | No | boolean | Should device be charging to run flag.
docked | No | boolean | Indicates Activity should only run when device is docked.

Example

>     {
>       "wifi"      : true,
>       "battery"   : 60,
>       "charging"  : true
>     }

## Schedule

The Schedule object defines an Activity's time-based requirements. The time an Activity is scheduled to run can be either absolute or local. If a local time is specified, the Activity Manager watches for time zone changes and automatically adjusts the UTC time.

Smart Intervals, specified with the interval field, allow tasks to be scheduled in evenly aligned batches, optimizing battery power and efficiency. Smart intervals are specified with the interval string field as "##d##h##m##s". Days (d), hours (h), minutes (m) and seconds (s) must be specified in order, but any can be left out. The 24h Activity slot is aligned at a random point between midnight and 2am local time (determined each time the device boots) to avoid excessive server access at midnight. It is recommended you use this if a precise interval is not required. Smart intervals must be specified as an even multiple of days, 1, 3, 6, or 12 hour intervals and 5, 10, or 15 minute intervals. All tasks on the interval are aligned at approximately the same time.

Starting can be delayed if additional Requirements are specified, or if a Trigger has yet to fire.

Most scheduled Activities should be background Activities.

Notes:

- All fields are optional though you must specify either start or interval.
- UTC time strings not ending in `Z` are interpreted as local time.

### Schema

>     {
>       "precise"  : boolean,
>       "start"    : string,
>       "interval" : string,
>       "skip"     : boolean,
>       "local"    : boolean,
>       "end"      : string
>     }

Element | Required | Type | Description
--- | --- | --- | ---
precise | No | boolean | Indicates the Interval occurs at the precisely specified start time, and every given interval thereafter.
start | No | string | Launch time. Time format is a subset of ISO 8601— "YYYY-MM-DD HH:MM:SS" (for local) or "YYYY-MM-DD HH:MM:SSZ" for UTC. This field is required for basic scheduled items, and optional for intervals. Launch time.
interval | No | string | Specifies the number of days, hours, minutes, and seconds— "##d##h##m##s"— between Activity execution. If set, then after an Activity is marked Complete, it is re-queued with a new start time. Days, hours, minutes and seconds must be specified in order, but any can be left out.
skip | No | boolean | If an interval Activity is not able to run, i.e., the device was off when scheduled to start, it runs (by default) at the first opportunity. However, if `skip` is `true` it waits for the next scheduled interval time to occur before running.
local | No | boolean | Indicates that a date/time NOT ending in 'Z' is local. This will become unnecessary once times not ending in 'Z' are interpreted as local by default.
end | No | string | End date/time for the interval.

Examples

#### Simple Scheduled Item

>     {
>       "start"    : "2010-05-27 13:22:00",
>       "local"    : true
>     }

#### Smart Interval

>     {
>       "interval" : "10d20h30m20s"
>     }

#### Precise Interval

>     {
>       "precise"  : true,
>       "start"    : "2010-07-20 14:22:00",
>       "interval" : "12d20h30m40s"
>       "start"    : "2010-11-20 12:00:00",
>       "skip"     : true,
>       "local"    : true
>     }

## State

Current Activity state.

Note the following about Activity state:

- When created, Activities are in the "init" state. Once the Activity's associations and initial app and service subscriptions are in place, it is issued a start command.

- If an Activity has a trigger, or has a scheduled start time specified with a schedule parameter, it enters the "waiting" state.

- Once an Activity's Trigger fires, or the Activity reaches its scheduled start time, the Activity exits the "waiting" state.

- If the Activity has requirements that must be met before it can run and they are not, the Activity enters the "blocked" state until they are and it is eligible to run.

- Foreground Activities immediately enter the "running" state, while Background Activities enter the "queued" state until needed resources to run become available.

- Activities can transition back and forth between the "queued" and "blocked" states depending on whether the system can provide their specified requirements.

- When an Activity enters the "running" state, all subscribers receive the "start" event, and the callback method, if present, is called.

### Schema

>     {
>       "init" | "waiting" | "blocked" | "queued" | "running" | "paused" |
>       "cancelling" | "cancelled" | "stopping" | "stopped" | "complete"
>     }

State | Description
--- | ---
`init` | Activity has been created and is waiting for Activity's associations and initial app and service subscriptions to be in place
`waiting` | Activity is waiting for a trigger to fire or its scheduled time to begin running.
`blocked` | Activity is waiting for its specified Requirements to be met.
`queued` | The Activity is queued and ready to run.
`running` | The Activity is running.
`pause` | The Activity is paused.
`cancelling` | The Activity has been cancelled and waiting for potential adopters to take over as the parent.
`cancelled` | The Activity is cancelled.
`stopping` | The Activity is in the process of stopping.
`stopped` | The Activity has been stopped.
`complete` | The Activity is complete and has stopped.

## Triggers

Activities with Triggers do not become runnable until an event occurs on a subscribed method. In addition, other requirements or scheduling constraints may also need to be met before the Activity is runnable. When the Activity starts, the specified method is called with "subscribe=true", and any additional arguments the Activity creator provides. If another Activity has previously been created and started with an identical Trigger (the same method and arguments) then the Activity Manager may utilize its existing subscription to monitor for the Triggering event, unless "unique" is true in the Trigger specification.

If the Trigger specification includes a `key` property, the Activity Manager looks for responses to
the Trigger method call that include the named `key` property. The Trigger fires when a response with that property is seen (including the initial response). The Trigger also fires if the Trigger method returns an error result—either the initial call result or any subsequent results. If a `key` property is not specified, the Trigger fires on the first response after the initial successful response.

An example of a key property would be the "fired" property that db8 returns in a notification that watched query results have changed.

Triggers are not "persistent subscriptions". The Trigger is unsubscribed after the response which causes it to fire is seen.

The Trigger fires on any error return result. Once it fires, the Trigger is unsubscribed. If a new Trigger is desired, your app should create a new Activity. When a subscription generates an event, the data is passed to the callback method as the "trigger" of the Activity Manager Callback Property that the Activity Manager adds to callbacks.

WARNING

Do NOT ignore the trigger information returned in a callback. If an error is returned to the method specified for a Trigger, then the Trigger fires immediately. This could happen if, for example, the parameters passed to the method were invalid or wrong. If the Trigger callback re-starts the Activity, i.e., in the case of a db8 watch, then the potential exists for an infinite loop. CHECK FOR ERRORS.

### Schema

Note: All fields are optional except "method".

>     {
>       "method" : string,
>       "key"    : string,
>       "params" : any,
>       "where"  : string or array of strings
>     }

See the db8 documentation for where clause specification.

### Elements

Element | Required | Type | Description
--- | --- | --- | ---
method | Yes | string | Name of callback method.
key | No | string | Key property name. Activity Manager looks for this field in callback response, i.e., "fired" from db8 watch where query results have changed.
params | No | any | Parameters for subscription or watch.
where | No | string or array of strings | Single db8 where clause or array of db8 where clauses.

Examples

Example 1

>     {
>       "method" : "palm://com.palm.connectionmanager/getStatus",  // Device status service
>       "params" : {"subscribe":true}
>     }

Example 2

>     {
>       "method" :  "palm://com.palm.telephony/phoneNumberQuery",
>       "params" :  { "subscribe" : true },
>       "where" :   {
>           "prop" : [ "extended", "number" ],
>           "op"   : "!=",
>           "val"  : "14155551212"
>       }
>     }

Example Response to Callback

>     {
>       "errorCode" : 0,
>       "errorString" : "success",
>       "extended" : {
>           "number" : "14155551212"
>       },
>       "returnValue" : true,
>       "subscribed" : true
>     }

## Type

Indicates how the Activity is handled. Principally, it is used to denote the Activity as either foreground or background, and whether it can be paused or cancelled.

### Foreground or Background

Default attributes are associated with background and foreground Activities:

- Foreground Activities are high priority and immediate— They cannot be queued and begin running when their prerequisites are met.
- Background Activities are low priority and not immediate—They are runnable, but queued until necessary resources become available.

Whether an activity is foreground or background should only be set once. The default is foreground. If your app specifies foreground or background, do NOT set the advanced attributes (immediate and priority). If you set them, thee Activity Manager will NOT create the Activity. If you do not set either foreground or background, then you MUST set "immediate" and "priority".

### Priority

Use "high" or "highest" priority if your Activity is performance critical, for example: 3D games, where failing to keep up with the desired frame rate is dramatically noticeable. Normal interactive UI Activities should use "normal". If immediate display is not critical to your app, say, for example, an email sync, "low" priority is appropriate since the user does not necessarily expect email to show up immediately when they hit the 'sync' button, so a little extra time is not a problem. In addition, the delay only happens if the device has other things to do; if your Activity is the only thing running, it gets all the CPU it needs.

### Probe Activity

As indicated with the "probe" flag, a probe Activity is one that does not impact resources, allowing many to run in parallel, rather than serially. You can use this in cases where more complex logic is required to determine if an Activity can proceed. Schedule the probe Activity to determine if the more heavy-weight Activity should proceed, and, if so, schedule the heavy-weight Activity with the Activity Manager and conclude the probe. For example, an email syncing app or service may first want to see if there is email to sync. Let's say there are 10 email accounts. The setup, login negotiation, and waiting for the server to respond might take 15-30 seconds. If done in sequence, it would take 5 minutes to discover if there was email to sync on all the accounts. Most of this involves waiting, so there is minimal CPU involved. It is also likely to be implemented in the same few services, so, in terms of memory use, doing five is probably as expensive as doing one. In this case, it is better to run them in parallel, find out which accounts had mail to sync, and then create new background Activities specifically to sync each account with mail.

### Persistent Activity

If "persist" is true, the Activity continue across device reboots. These Activities are atomically updated and re-scheduled across version updates and device or services crashes.

### Explicit Activity

If "explicit" is true, the Activity can only be terminated with a stop, cancel, or complete call. If the parent of an explicit Activity unsubscribes, and no other adopter is available, then, instead of being cancelled (the default), the Activity is moved back to the ready state and its callback is invoked.

### Schema

Note: All fields are optional, but if you do not set "foreground" or "background", then you must set "immediate" and "priority".

>     {
>       "foreground" | "background" : boolean |
>       "immediate"     : boolean,
>       "priority"      : string,
>       "userInitiated" : boolean,
>       "pausable"      : boolean,
>       "cancellable"   : boolean,
>       "probe"         : boolean,
>       "persist"       : boolean,
>       "explicit"      : boolean,
>       "continuous"    : boolean,
>       "power"         : boolean,
>       "powerDebounce" : boolean
>     }

### Elements

Element | Required | Type | Description
--- | --- | --- | ---
foreground | No | boolean | Activity runs in the foreground and starts running when its prerequisites are met. Set either this or background, or immediate and priority.
background | No | boolean | Activity runs in the background. When its prerequisites are met it's placed into a ready queue and runs as system resources allow. Set either this or foreground, or immediate and priority.
immediate | No | boolean | Activity should run immediately. Set either this and priority, or background or foreground.
priority | No | string | Indicates Activity's priority. Must be one of the following: "highest", "high", "normal", "low", or "lowest". Set either this and immediate, or background or foreground.
userInitiated | No | boolean | Not currently used.
pausable | No | boolean | Activity subscribers are prepared to handle pause event.
cancellable | No | boolean | Activity subscribers are prepared to handle cancel event.
probe | No | boolean | Short duration Activity using minimal resources that determines if another Activity should be scheduled.
persist | No | boolean | Store Activity state in db8 so it can span reboots, loss of service, or updates.
explicit | No | boolean | Activity is restarted unless terminated with complete, stop, or cancel.
continuous | No | boolean | Activity does not have a well defined ending point and could run indefinitely.
power | No | boolean | Activity requires device remain powered while it is running.
powerDebounce | No | boolean | Events associated with this Activity are due to complete shortly. Set this flag to keep the device from having to suspend/restart in the meantime.

Example

>     {
>       "foreground"    : true,
>       "userInitiated" : false,
>       "pausable"      : true,
>       "cancellable"   : true,
>       "probe"         : false,
>       "persist"       : true,
>       "explicit"      : true,
>       "continuous"    : true,
>       "power"         : false,
>       "powerDebounce" : false
>     }