Anda di halaman 1dari 148

LAMPIRAN : DAFTAR PHONEGAP

API(HTTP://DOCS.PHONEGAP.COM)

Sejauh ini kita telah belajar banyak tentang pembuatan aplikasi android dan iphone dengan menggunakan javascript, HTML dan css.

Contoh project yang telah sama sama kita bahas tidak memanfaatkan seluruh phonegap API yang tersedia. Ya tentu saja, kita belum tentu memerlukan semua API yang disediakan dalam satu aplikasi yang kita buat.

Akan tetapi saya merasa perlu menekankan kepada para pembaca buku ini bahwa seorang pengembang software yang baik adalah seorang yang tidak segan-segan membaca dan mempelajari dokumentasi API yang telah disediakan.

Oleh karenanya saya memberikan lampiran phonegap API yang lengkap untuk memudahkan kepada pembaca buku dalam mempelajarinya.

Lampiran ini jadikan sebagai referensi ketika tiba tiba Anda membutuhkan untuk mengakses phonegap API.

A. Accelerometer

Captures device motion in the x, y, and z direction.

1

Methods

1. accelerometer.getCurrentAcceleration

2. accelerometer.watchAcceleration

3. accelerometer.clearWatch

Arguments

1. accelerometerSuccess

2. accelerometerError

3. accelerometerOptions

Objects (Read-Only)

1. Acceleration

accelerometer.getCurrentAcceleration

Get the current acceleration along the x, y, and z axis.

navigator.accelerometer.getCurrentAcceleration(acce

navigator.accelerometer.getCurrentAcceleration(acce

lerometerSuccess, accelerometerError);

navigator.accelerometer.getCurrentAcceleration(acce lerometerSuccess, accelerometerError);

Description

The accelerometer is a motion sensor that detects the change (delta) in movement relative to the current device orientation. The accelerometer can detect 3D movement along the x, y, and z axis.

The

function.

Supported Platforms

using the accelerometerSuccess callback

acceleration

is

returned

1. Android

2. BlackBerry WebWorks (OS 5.0 and higher)

3. iPhone

Quick Example

2

function onSuccess(acceleration) {

alert('Acceleration X: ' + acceleration.x +

'\n' +

 
 

'Acceleration Y:

'

+ acceleration.y +

'\n' +

 
 

'Acceleration

Z:

'

+ acceleration.z +

'\n' +

 
 

'Timestamp:

'

+

acceleration.timestamp + '\n');

 
};
};

function onError() {

alert('onError!');

};
};
navigator.accelerometer.getCurrentAcceleration(onSu

navigator.accelerometer.getCurrentAcceleration(onSu

ccess, onError);

navigator.accelerometer.getCurrentAcceleration(onSu ccess, onError);

iPhone Quirks

1. iPhone doesn't have the concept of getting the current acceleration at any given point.

2. You must watch the acceleration and capture the data at given time intervals.

3. Thus, the getCurrentAcceleration function will give you the last value reported from a phoneGap watchAccelerometer call.

accelerometer.watchAcceleration

At a regular interval, get the acceleration along the x, y, and z axis.

var

watchID

=

navigator.accelerometer.watchAcceleration(accelerom

eterSuccess,

accelerometerError,

[accelerometerOptions]);

3

Description

The accelerometer is a motion sensor that detects the change (delta) in movement relative to the current position. The accelerometer can detect 3D movement along the x, y, and z axis.

The accelerometer.watchAcceleration gets the device's current acceleration at a regular interval. Each time the Acceleration is retrieved, the accelerometerSuccess callback function is executed. Specify the interval in milliseconds via the frequency parameter in the acceleratorOptions object.

The returned watch ID references references the accelerometer watch interval. The watch ID can be used with accelerometer.clearWatch to stop watching the accelerometer.

Supported Platforms

1. Android

2. BlackBerry WebWorks (OS 5.0 and higher)

3. iPhone

Quick Example

function onSuccess(acceleration) {

alert('Acceleration X: ' + acceleration.x +

'\n' +

 
 

'Acceleration

Y:

'

+ acceleration.y +

'\n' +

 
 

'Acceleration

Z:

'

+ acceleration.z +

'\n' +

 
 

'Timestamp:

 

'

+

acceleration.timestamp + '\n');

 
};
};

function onError() {

 

alert('onError!');

 
};
};

4

var options = { frequency: 3000 };

// Update every

3 seconds

 

var

 

watchID

=

navigator.accelerometer.watchAcceleration(onSuccess

 

,

onError, options);

 

iPhone Quirks

1. At the interval requested, PhoneGap will call the success callback function and pass the accelerometer results.

2. However, in requests to the device PhoneGap restricts the interval to minimum of every 40ms and a maximum of every 1000ms.

a. For example, if you request an interval of 3 seconds (3000ms), PhoneGap will request an interval of 1 second from the device but invoke the success callback at the requested interval of 3 seconds.

accelerometer.clearWatch

Stop watching the Acceleration referenced by the watch ID parameter.

navigator.accelerometer.clearWatch(watchID);

watchID: The ID returned by accelerometer.watchAcceleration.

Supported Platforms

1. Android

2. BlackBerry WebWorks (OS 5.0 and higher)

3. iPhone

Quick Example

var

watchID

=

navigator.accelerometer.watchAcceleration(onSuccess

 

,

onError, options);

 
 

5

//

later on

navigator.accelerometer.clearWatch(watchID);

Acceleration

Contains Accelerometer data captured at a specific point in time.

Properties

1. x: Amount of motion on the x-axis. Range [0, 1] (Number)

2. y: Amount of motion on the y-axis. Range [0, 1] (Number)

3. z: Amount of motion on the z-axis. Range [0, 1] (Number)

4. timestamp: Creation timestamp in milliseconds. (DOMTimeStamp)

Description

This object is created and populated by PhoneGap, and returned by an Accelerometer method.

Supported Platforms

1. Android

2. BlackBerry WebWorks (OS 5.0 and higher)

3. iPhone

Quick Example

function onSuccess(acceleration) {

alert('Acceleration X: ' + acceleration.x +

'\n' +

 
 

'Acceleration

Y:

'

+ acceleration.y +

'\n' +

 

6

 

'Acceleration

Z:

' + acceleration.z

+

'\n' +

 
 

'Timestamp:

'

+

acceleration.timestamp + '\n');

 
};
};

function onError() {

alert('onError!');

};
};
navigator.accelerometer.getCurrentAcceleration(onSu

navigator.accelerometer.getCurrentAcceleration(onSu

ccess, onError);

navigator.accelerometer.getCurrentAcceleration(onSu ccess, onError);

accelerometerSuccess

onSuccess callback function that

provides the

Acceleration information.

 

function(acceleration) {

// Do something

}
}

Parameters

acceleration: The acceleration at a single moment in time. (Acceleration)

Example

function onSuccess(acceleration) {

alert('Acceleration X: ' + acceleration.x +

alert('Acceleration X: ' + acceleration.x +

'\n' +

alert('Acceleration X: ' + acceleration.x + '\n' +

7

 

'Acceleration

Y:

'

+ acceleration.y +

'\n' +

 
 

'Acceleration

Z:

'

+ acceleration.z +

'\n' +

 
 

'Timestamp:

'

+

acceleration.timestamp + '\n');

 
};
};

accelerometerError

 

onError

callback

function

for

acceleration

functions.

 

function() {

 

// Handle the error

}

accelerometerOptions

An optional parameter to customize the retrieval of the accelerometer.

Options

frequency: How often to retrieve the Acceleration in milliseconds. (Number) (Default:10000)

B. Camera

The camera object provides access to the device's default camera application.

Methods

camera.getPicture

8

camera.getPicture

Takes a photo using the camera or retrieves a photo from the device's album. The image is returned as a base64 encoded String or as the URI of an image file.

navigator.camera.getPicture( cameraSuccess, cameraError, [ cameraOptions ] );

Description

Function camera.getPicture opens the device's default camera application so that the user can take a picture (if Camera.sourceType = Camera.PictureSourceType.CAMERA, which is the default). Once the photo is taken, the camera application closes and your application is restored.

If Camera.sourceType = Camera.PictureSourceType.PHOTOLIBRARY or Camera.PictureSourceType.SAVEDPHOTOALBUM, then a photo chooser dialog is shown, from which a photo from the album can be selected.

The return value will be sent to the cameraSuccess function, in one of the following formats, depending on the cameraOptions you specify:

A String containing the Base64 encoded photo image (default).

A String representing the image file location on local storage. You can do whatever you want with the encoded image or URI, for example:

Render the image in an <img> tag (see example below)

Save the data locally (LocalStorage, Lawnchair, etc)

Post the data to a remote server Note: The image quality of pictures taken using the camera on newer devices is quite good. Encoding such images using Base64 has caused memory issues on some of these devices (iPhone 4, BlackBerry Torch 9800). Therefore, using FILE_URI as the 'Camera.destinationType' is highly recommended.

Supported Platforms

9

Android

Blackberry WebWorks (OS 5.0 and higher)

iPhone

Quick Example

Take photo and retrieve Base64-encoded image:

navigator.camera.getPicture(onSuccess, onFail, { quality: 50 }); function onSuccess(imageData) { var image =
navigator.camera.getPicture(onSuccess,
onFail,
{
quality: 50 });
function onSuccess(imageData) {
var image = document.getElementById('myImage');
image.src
=
"data:image/jpeg;base64,"
+
imageData;
}
function onFail(message) {
alert('Failed because: ' + message);
}
Take photo and retrieve image file location:
navigator.camera.getPicture(onSuccess,
onFail,
{
quality: 50,

destinationType:

destinationType: Camera.DestinationType.FILE_URI });
Camera.DestinationType.FILE_URI });

Camera.DestinationType.FILE_URI });

function onSuccess(imageURI) {

var image = document.getElementById('myImage');

image.src = imageURI;

}
}

function onFail(message) {

alert('Failed because: ' + message);

}
}

10

cameraSuccess

onSuccess callback function that provides the image

onSuccess callback function that provides the image

data.

onSuccess callback function that provides the image data.

function(imageData) {

// Do something with the image

}
}

Parameters

imageData: Base64 encoding of the image data, OR the image file URI, depending on cameraOptions used. (String)

Example // Show image //
Example
// Show image
//

function cameraCallback(imageData) {

var image = document.getElementById('myImage');

image.src

=

"data:image/jpeg;base64,"

+

imageData;

}
}

cameraError

onError callback function that provides an error

onError callback function that provides an error

message.

onError callback function that provides an error message.

function(message) {

// Show a helpful message

}
}

Parameters

11

message: The message is provided by the device's native code. (String)

cameraOptions

Optional parameters to customize the camera settings.

{ quality : 75,

destinationType

:

Camera.DestinationType.DATA_URL,

sourceType : Camera.PictureSourceType.CAMERA,

allowEdit : true,

encodingType: Camera.EncodingType.JPEG,

targetWidth: 100,

targetHeight: 100 };

Options

quality: Quality of saved image. Range is [0, 100]. (Number) destinationType: Choose the format of the return value. Defined in navigator.camera.DestinationType (Number) Camera.DestinationType = {

DATA_URL : 0, FILE_URI : 1

// Return image as base64 encoded string // Return image file URI

}; sourceType: Set the source of the picture. Defined in nagivator.camera.PictureSourceType (Number) Camera.PictureSourceType = { PHOTOLIBRARY : 0, CAMERA : 1, SAVEDPHOTOALBUM : 2

};

allowEdit: Allow simple editing of image before selection. (Boolean) EncodingType: Choose the encoding of the returned image file. Defined in navigator.camera.EncodingType (Number) Camera.EncodingType = {

JPEG : 0,

// Return JPEG encoded image

12

PNG : 1

// Return PNG encoded image

}; targetWidth: Width in pixels to scale image. Must be used with targetHeight. Aspect ratio is maintained. (Number) targetHeight: Height in pixels to scale image. Must be used with targetWidth. Aspect ratio is maintained. (Number)

Android Quirks

Ignores the allowEdit parameter.

Camera.PictureSourceType.PHOTOLIBRARY and Camera.PictureSourceType.SAVEDPHOTOALBUM both display the same photo album.

Camera.EncodingType is not supported.

BlackBerry Quirks

Ignores the quality parameter.

Ignores the sourceType parameter.

Ignores the allowEdit parameter.

Application must have key injection permissions to close native Camera application after photo is taken.

Using Large image sizes may result in inability to encode image on later model devices with high resolution cameras (e.g. Torch 9800).

Palm Quirks

Ignores the quality parameter.

Ignores the sourceType parameter.

Ignores the allowEdit parameter.

iPhone Quirks

Set quality below 50 to avoid memory error on some devices.

When destinationType.FILE_URI is used, photos are saved in the application's temporary directory.

13

The contents of the application's temporary directory is deleted when the application ends. Developers may also delete the contents of this directory using the navigator.fileMgr APIs if storage space is a concern.

C. Capture

Provides access to the audio, image, and video capture capabilities of the device.

Objects

Capture

CaptureAudioOptions

CaptureImageOptions

CaptureVideoOptions

CaptureCB

CaptureErrorCB

ConfigurationData

MediaFile

MediaFileData

Methods

capture.captureAudio

capture.captureImage

capture.captureVideo

MediaFile.getFormatData

Scope

14

The capture object is assigned to the navigator.device object, and therefore has global scope.

// The global capture object

var capture = navigator.device.capture;

Properties

supportedAudioModes: The audio recording formats supported by the device. (ConfigurationData[])

supportedImageModes: The recording image sizes and formats supported by the device. (ConfigurationData[])

supportedVideoModes: The recording video resolutions and formats supported by the device. (ConfigurationData[])

Methods

capture.captureAudio: Launch the device audio recording application for recording audio clip(s).

capture.captureImage: Launch the device camera application for taking image(s).

capture.captureVideo: Launch the device video recorder application for recording video(s).

Supported Platforms

Android

BlackBerry WebWorks (OS 5.0 and higher)

iOS

capture.captureAudio

Start the audio recorder application and return information about captured audio clip file(s).

navigator.device.capture.captureAudio(

15

CaptureCB

captureSuccess,

CaptureErrorCB

captureError, [CaptureAudioOptions options]

);
);

Description

This method starts an asynchronous operation to capture audio recordings using the device's default audio recording application. The operation allows the device user to capture multiple recordings in a single session.

The capture operation ends when either the user exits the audio recording application, or the maximum number of recordings, specified by the limit parameter in CaptureAudioOptions, has been reached. If no value is provided for the limit parameter, a default value of one (1) is used, and the capture operation will terminate after the user records a single audio clip.

When the capture operation is finished, it will invoke the CaptureCB callback with an array of MediaFile objects describing each captured audio clip file. If the operation is terminated by the user before an audio clip is captured, the CaptureErrorCB callback will be invoked with a CaptureError object with the CaptureError.CAPTURE_NO_MEDIA_FILES error code.

Supported Platforms

Android

BlackBerry WebWorks (OS 5.0 and higher)

iOS

Quick Example

// capture callback

var captureSuccess = function(mediaFiles) {

var i, path, len;

for (i = 0, len = mediaFiles.length; i < len; i

for (i = 0, len = mediaFiles.length; i < len; i

+= 1) {

for (i = 0, len = mediaFiles.length; i < len; i += 1) {

path = mediaFiles[i].fullPath;

// do something interesting with the file

16

} };
}
};

// capture error callback

var captureError = function(error) {

navigator.notification.alert('Error code: ' +

navigator.notification.alert('Error code: ' +

error.code, null, 'Capture Error');

navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error');
};
};

// start audio capture

navigator.device.capture.captureAudio(captureSucces

navigator.device.capture.captureAudio(captureSucces

s, captureError, {limit:2});

navigator.device.capture.captureAudio(captureSucces s, captureError, {limit:2});

BlackBerry WebWorks Quirks

PhoneGap for BlackBerry WebWorks attempts to launch the Voice Notes Recorder application, provided by RIM, to capture the audio recordings. The developer will receive a CaptureError.CAPTURE_NOT_SUPPORTED error code if the application is not installed on the device.

iOS Quirks

iOS does not have a default audio recording application so a simple user interface is provided.

CaptureAudioOptions

Encapsulates audio capture configuration options.

Properties

17

limit: The maximum number of audio clips the device user can record in a single capture operation. The value must be greater than or equal to 1 (defaults to 1).

duration: The maximum duration of an audio sound clip, in seconds.

mode: The selected audio mode. The value must match one of the elements in capture.supportedAudioModes.

Quick Example

// limit capture operation to 3 media files, no

// limit capture operation to 3 media files, no

longer than 10 seconds each

// limit capture operation to 3 media files, no longer than 10 seconds each

var options = { limit: 3, duration: 10 };

navigator.device.capture.captureAudio(captureSucces

navigator.device.capture.captureAudio(captureSucces

s, captureError, options);

navigator.device.capture.captureAudio(captureSucces s, captureError, options);

Android Quirks

The duration parameter is not supported. Recording lengths cannot be limited programmatically.

The mode parameter is not supported. The audio recording format cannot be altered programmatically. Recordings are encoded using Adaptive Multi-Rate (AMR) format (audio/amr).

BlackBerry WebWorks Quirks

The duration parameter is not supported. Recording lengths cannot be limited programmatically.

The mode parameter is not supported. The audio recording format cannot be altered programmatically. Recordings are encoded using Adaptive Multi-Rate (AMR) format (audio/amr).

iOS Quirks

18

The limit parameter is not supported. One recording can be created for each invocation.

The mode parameter is not supported. The audio recording format cannot be altered programmatically. Recordings are encoded using Waveform Audio (WAV) format (audio/wav).

capture.captureImage

Start the camera application and return information about captured image file(s).

navigator.device.capture.captureImage(

CaptureCB

captureSuccess,

CaptureErrorCB

captureError, [CaptureImageOptions options]

);
);

Description

This method starts an asynchronous operation to capture images using the device camera application. The operation allows the device user to capture multiple images in a single session.

The capture operation ends when either the user exits the camera application, or the maximum number of images, specified by the limit parameter in CaptureImageOptions, has been reached. If no value is provided for the limit parameter, a default value of one (1) is used, and the capture operation will terminate after the user captures a single image.

When the capture operation is finished, it will invoke the CaptureCB callback with an array of MediaFile objects describing each captured image file. If the operation is terminated by the user before an image is captured, the CaptureErrorCB callback will be invoked with a CaptureError object with the CaptureError.CAPTURE_NO_MEDIA_FILES error code.

Supported Platforms

Android

BlackBerry WebWorks (OS 5.0 and higher)

19

iOS

Quick Example

// capture callback

var captureSuccess = function(mediaFiles) {

var i, path, len;

for (i = 0, len = mediaFiles.length; i < len; i

for (i = 0, len = mediaFiles.length; i < len; i

+= 1) {

for (i = 0, len = mediaFiles.length; i < len; i += 1) {

path = mediaFiles[i].fullPath;

// do something interesting with the file

} };
}
};

// capture error callback

var captureError = function(error) {

navigator.notification.alert('Error code: ' +

navigator.notification.alert('Error code: ' +

error.code, null, 'Capture Error');

navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error');
};
};

// start image capture

navigator.device.capture.captureImage(captureSucces

navigator.device.capture.captureImage(captureSucces

s, captureError, {limit:2});

navigator.device.capture.captureImage(captureSucces s, captureError, {limit:2});

CaptureImageOptions

Encapsulates image capture configuration options.

Properties

20

limit: The maximum number of images the device user can capture in a single capture operation. The value must be greater than or equal to 1 (defaults to 1).

mode: The selected image mode. The value must match one of the elements in capture.supportedImageModes.

Quick Example

// limit capture operation to 3 images

var options = { limit: 3 };

navigator.device.capture.captureImage(captureSuccess,

options);

Android Quirks

captureError,

The mode parameter is not supported. The image size and format cannot be altered programmatically; however, the image size can be altered by the device user. Images are saved in JPEG format (image/jpeg).

BlackBerry WebWorks Quirks

The mode parameter is not supported. The image size and format cannot be altered programmatically; however, the image size can be altered by the device user. Images are saved in JPEG format (image/jpeg).

iOS Quirks

The limit parameter is not supported. One image is taken per invocation.

The mode parameter is not supported. The image size and format cannot be altered programmatically. Images are saved in JPEG format (image/jpeg).

21

capture.captureVideo

Start the video recorder application and return information about captured video clip file(s).

navigator.device.capture.captureVideo(

CaptureCB

captureSuccess,

CaptureErrorCB

captureError, [CaptureVideoOptions options]

);
);

Description

This method starts an asynchronous operation to capture video recordings using the device video recording application. The operation allows the device user to capture multiple recordings in a single session.

The capture operation ends when either the user exits the video recording application, or the maximum number of recordings, specified by the limit parameter in CaptureVideoOptions, has been reached. If no value is provided for the limit parameter, a default value of one (1) is used, and the capture operation will terminate after the user records a single video clip.

When the capture operation is finished, it will invoke the CaptureCB callback with an array of MediaFile objects describing each captured video clip file. If the operation is terminated by the user before an video clip is captured, the CaptureErrorCB callback will be invoked with a CaptureError object with the CaptureError.CAPTURE_NO_MEDIA_FILES error code.

Supported Platforms

Android

BlackBerry WebWorks (OS 5.0 and higher)

iOS

Quick Example

// capture callback

var captureSuccess = function(mediaFiles) {

22

var i, path, len;

for (i = 0, len = mediaFiles.length; i < len; i

for (i = 0, len = mediaFiles.length; i < len; i

+= 1) {

for (i = 0, len = mediaFiles.length; i < len; i += 1) {

path = mediaFiles[i].fullPath;

// do something interesting with the file

} };
}
};

// capture error callback

var captureError = function(error) {

navigator.notification.alert('Error code: ' +

navigator.notification.alert('Error code: ' +

error.code, null, 'Capture Error');

navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error');
};
};

// start video capture

navigator.device.capture.captureVideo(captureSucces

navigator.device.capture.captureVideo(captureSucces

s, captureError, {limit:2});

navigator.device.capture.captureVideo(captureSucces s, captureError, {limit:2});

BlackBerry WebWorks Quirks

PhoneGap for BlackBerry WebWorks attempts to launch the Video Recorder application, provided by RIM, to capture the video recordings. The developer will receive a CaptureError.CAPTURE_NOT_SUPPORTED error code if the application is not installed on the device.

CaptureVideoOptions

Encapsulates video capture configuration options.

Properties

23

limit: The maximum number of video clips the device user can capture in a single capture operation. The value must be greater than or equal to 1 (defaults to 1).

duration: The maximum duration of a video clip, in seconds.

mode: The selected video capture mode. The value must match one of the elements in capture.supportedVideoModes.

Quick Example

// limit capture operation to 3 video clips

var options = { limit: 3 };

navigator.device.capture.captureVideo(captureSucces

navigator.device.capture.captureVideo(captureSucces

s, captureError, options);

navigator.device.capture.captureVideo(captureSucces s, captureError, options);

Android Quirks

The duration parameter is not supported. Recording lengths cannot be limited programmatically.

The mode parameter is not supported. The video size and format cannot be altered programmatically; however, these parameters can be changed by the device user. By default, videos are recorded in 3GPP (video/3gpp) format.

BlackBerry WebWorks Quirks

The duration parameter is not supported. Recording lengths cannot be limited programmatically.

The mode parameter is not supported. The video size and format cannot be altered programmatically; however, these parameters can be changed by the device user. By default, videos are recorded in 3GPP (video/3gpp) format.

iOS Quirks

24

The limit parameter is not supported. One video is recorded per invocation.

The duration parameter is not supported. Recording lengths cannot be limited programmatically.

The mode parameter is not supported. The video size and format cannot be altered programmatically. By default, videos are recorded in MOV (video/quicktime) format.

CaptureCB

Invoked upon a successful media capture operation.

function captureSuccess( MediaFile[] mediaFiles ) {

Description

};

This function is invoked after a successful capture operation has completed. This means a media file has been captured, and either the user has exited the media capture application, or the capture limit has been reached.

Each MediaFile object describes a captured media file.

Quick Example

// capture callback

function captureSuccess(mediaFiles) {

var i, path, len;

for (i = 0, len = mediaFiles.length; i < len; i

for (i = 0, len = mediaFiles.length; i < len; i

+= 1) {

for (i = 0, len = mediaFiles.length; i < len; i += 1) {

path = mediaFiles[i].fullPath;

// do something interesting with the file

} };
}
};

CaptureErrorCB

25

Invoked if an error occurs during a media capture operation.

function captureError( CaptureError error ) {

};

Description

This function is invoked if an error occurs when trying to launch a media capture operation and the capture application is busy, if an error occurs while the capture operation is taking place, or if the capture operation has been canceled by the user before any media files have been captured.

This function is invoked with a CaptureError object containing an appropriate error code.

Quick Example

// capture error callback

var captureError = function(error) {

navigator.notification.alert('Error code: ' +

navigator.notification.alert('Error code: ' +

error.code, null, 'Capture Error');

navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error');
};
};

ConfigurationData

Encapsulates a set of media capture parameters that a device supports.

Description

This object is used to describe media capture modes supported by the device. The configuration data includes the MIME type, and capture dimensions (for video or image capture).

The MIME types should adhere to RFC2046. Examples:

video/3gpp

video/quicktime

image/jpeg

audio/amr

26

audio/wav

Properties

type: The ASCII-encoded string in lower case representing the media type. (DOMString)

height: The height of the image or video in pixels. In the case of a sound clip, this attribute has value 0. (Number)

width: The width of the image or video in pixels. In the case of a sound clip, this attribute has value 0. (Number)

Quick Example

// retrieve supported image modes

var

imageModes

=

navigator.device.capture.supportedImageModes;

 

//

Select mode

that has the highest horizontal

resolution

 

var width = 0;

var selectedmode;

for each (var mode in imageModes) {

if (mode.width > width) {

width = mode.width;

selectedmode = mode;

} }
}
}

Not supported by any platform. All configuration data arrays are empty.

MediaFile

Encapsulates properties of a media capture file.

27

Properties

name: The name of the file, without path information. (DOMString)

fullPath: The full path of the file, including the name. (DOMString)

type: The mime type (DOMString)

lastModifiedDate: The date and time that the file was last modified. (Date)

size: The size of the file, in bytes. (Number)

Methods

MediaFile.getFormatData: Retrieves the format information of the media file.

MediaFile.getFormatData

Retrieves format information about the media capture file.

mediaFile.getFormatData(

MediaFileDataSuccessCB successCallback,

[MediaFileDataErrorCB errorCallback]

);
);

Description

This function asynchronously attempts to retrieve the format information for the media file. If successful, it invokes the MediaFileDataSuccessCB callback with a MediaFileData object. If the attempt fails, this function will invoke the MediaFileDataErrorCB callback.

Supported Platforms

Android

BlackBerry WebWorks (OS 5.0 and higher)

iOS

28

BlackBerry WebWorks Quirks

There is no API that provides format information of media files. Therefore, all MediaFileData objects will be returned with default values. See MediaFileData documentation.

Android Quirks

The API for retrieving media file format information is limited. Therefore, not all MediaFileData properties are supported. See MediaFileData documentation.

iOS Quirks

The API for retrieving media file format information is limited. Therefore, not all MediaFileData properties are supported. See MediaFileData documentation.

MediaFileData

Encapsulates format information about a media file.

Properties

codecs: The actual format of the audio and video content. (DOMString)

bitrate: The average bitrate of the content. In case of an image, this attribute has value 0. (Number)

height: The height of the image or video in pixels. In the case of a sound clip, this attribute has value 0. (Number)

width: The width of the image or video in pixels. In the case of a sound clip, this attribute has value 0. (Number)

duration: The length of the video or sound clip in seconds. In the case of an image, this attribute has value 0. (Number)

BlackBerry WebWorks Quirks

29

There is no API that provides format information of media files. So the MediaFileData object returned by the MediaFile.getFormatData function will have the following default values:

codecs: Not supported. The attribute will always be null.

bitrate: Not supported. The attribute will always be 0.

height: Not supported. The attribute will always be 0.

width: Not supported. The attribute will always be 0.

duration: Not supported. The attribute will always be 0.

Android Quirks

Support for the MediaFileData properties is as follows:

codecs: Not supported. The attribute will always be null.

bitrate: Not supported. The attribute will always be 0.

height: Supported. (Image and video files only).

width: Supported. (Image and video files only).

duration: Supported. (Audio and video files only).

iOS Quirks

Support for the MediaFileData properties is as follows:

codecs: Not supported. The attribute will always be null.

bitrate: Supported on iOS4 devices for audio only. The attribute will always be 0 for image and video.

height: Supported. (Image and video files only).

width: Supported. (Image and video files only).

duration: Supported. (Audio and video files only).

D. Compass

Obtains the direction that the device is pointing.

Methods

30

compass.getCurrentHeading

compass.watchHeading

compass.clearWatch

Arguments

compassSuccess

compassError

compassOptions

compass.getCurrentHeading

Get the current compass heading.

navigator.compass.getCurrentHeading(compassSuccess,

compassOptions);

compassError,

Description

The compass is a sensor that detects the direction or heading that the device is pointed. It measures the heading in degrees from 0 to 359.99.

The

function.

using the compassSuccess callback

compass

heading

is

returned

Supported Platforms

Android

iPhone

Quick Example

function onSuccess(heading) {

alert('Heading: ' + heading);

};
};

31

function onError() {

alert('onError!');

};
};
navigator.compass.getCurrentHeading(onSuccess,

navigator.compass.getCurrentHeading(onSuccess,

onError);

navigator.compass.getCurrentHeading(onSuccess, onError);

compass.watchHeading

At a regular interval, get the compass heading in degrees.

var

watchID

=

navigator.compass.watchHeading(compassSuccess,

 

compassError, [compassOptions]);

 

Description

The compass is a sensor that detects the direction or heading that the device is pointed. It measures the heading in degrees from 0 to 359.99.

The compass.watchHeading gets the device's current heading at a regular interval. Each time the heading is retrieved, the headingSuccess callback function is executed. Specify the interval in milliseconds via the frequency parameter in the compassOptions object.

The returned watch ID references references the compass watch interval. The watch ID can be used with compass.clearWatch to stop watching the compass.

Supported Platforms

Android

iPhone

Quick Example

32

function onSuccess(heading) {

var

element

=

document.getElementById('heading');

element.innerHTML = 'Heading: ' + heading;

};
};

function onError() {

alert('onError!');

};
};

var options = { frequency: 3000 };

// Update every

3 seconds

 

var

watchID

=

navigator.compass.watchHeading(onSuccess,

onError,

options);

 

compass.clearWatch

 

Stop watching the compass referenced by the watch ID parameter.

 

navigator.compass.clearWatch(watchID);

 

watchID: The ID returned by compass.watchHeading.

Supported Platforms

 
 

Android

iPhone

Quick Example

var

watchID

=

navigator.compass.watchHeading(onSuccess,

onError,

options);

 

//

later on

 
 

33

navigator.compass.clearWatch(watchID);

compassSuccess

onSuccess callback

function

that

provides the

compass heading information.

 

function(heading) {

// Do something

}
}

Parameters

heading: The heading in degrees from 0 - 359.99 at a single moment in time. (Number)

Example

function onSuccess(heading) {

alert('Heading: ' + heading);

};
};

compassError

onError callback function for compass functions.

function() {

// Handle the error

}
}

compassOptions

An optional parameter to customize the retrieval of the compass.

34

Options

frequency: How often to retrieve the compass heading in milliseconds. (Number) (Default: 100)

E. Connection

The connection object gives access to the device's cellular and wifi connection information.

This object is accessed under the navigator.network interface.

Properties

connection.type

Constants

Connection.UNKNOWN

Connection.ETHERNET

Connection.WIFI

Connection.CELL_2G

Connection.CELL_3G

Connection.CELL_4G

Connection.NONE

connection.type

Checks the active network connection that is being used.

Description

This property is a fast way to determine the device's network connection state, and type of connection.

35

Supported Platforms

iOS

Android

BlackBerry WebWorks (OS 5.0 and higher)

Quick Example

function checkConnection() {

var networkState = navigator.network.connection.type; var states = {}; states[Connection.UNKNOWN] = 'Unknown
var
networkState
=
navigator.network.connection.type;
var states = {};
states[Connection.UNKNOWN]
=
'Unknown
connection';
states[Connection.ETHERNET]
=
'Ethernet
connection';
states[Connection.WIFI]
=
'WiFi
connection';
states[Connection.CELL_2G]
=
'Cell
2G
connection';
states[Connection.CELL_3G]
=
'Cell
3G
connection';
states[Connection.CELL_4G]
=
'Cell
4G
connection';
states[Connection.NONE]
=
'No
network
connection';
alert('Connection
type:
'
+
states[networkState]);
}
checkConnection();
F. Contacts
36

The contacts object provides access to the device contacts database.

Methods

contacts.create

contacts.find

Arguments

contactFields

contactSuccess

contactError

contactFindOptions

Objects

Contact

ContactName

ContactField

ContactAddress

ContactOrganization

ContactFindOptions

ContactError

contacts.create

Returns a new Contact object.

var

contact

=

navigator.contacts.create(properties);

 

Description

contacts.create is a synchronous function that returns a new Contact object.

 

37

This method does not persist the Contact object to the device contacts database. To persist the Contact object to the device, invoke the Contact.save method.

Supported Platforms

Android

BlackBerry WebWorks (OS 5.0 and higher)

iOS

Quick Example

var myContact = navigator.contacts.create({"displayName": "Test User"});

contacts.find

Queries the device contacts database and returns one or more Contact objects, each containing the fields specified.

contactError,

contactFindOptions);

navigator.contacts.find(contactFields,

contactSuccess,

Description

contacts.find is an asynchronous function that queries the device contacts database and returns an array of Contact objects. The resulting objects are passed to the contactSuccess callback function specified by the contactSuccess parameter.

Users must specify the contact fields to be used as a search qualifier in the contactFields parameter. Only the fields specified in the contactFieldsparameter will be returned as properties of the Contact objects that are passed to the contactSuccess callback function. A zero-length contactFields parameter will result in an array of Contact objects with only the id property populated. A contactFields value of ["*"] will return all contact fields.

The contactFindOptions.filter string can be used as a search filter when querying the contacts database. If provided, a case-insensitive, partial value match is applied to each field specified in the contactFields parameter. If a

38

match is found in a comparison with any of the specified fields, the contact is returned.

Parameters

contactFields: Contact fields to be used as search qualifier. Only these fields will have values in the resulting Contact objects. (DOMString[]) [Required]

contactSuccess: Success callback function that is invoked with the contacts returned from the contacts database. [Required]

contactError: Error callback function. Invoked when error occurs. [Optional]

contactFindOptions: Search options to filter contacts. [Optional]

Supported Platforms

Android

BlackBerry WebWorks (OS 5.0 and higher)

iOS

Quick Example

function onSuccess(contacts) {

alert('Found ' + contacts.length + ' contacts.'); }; function onError(contactError) {
alert('Found
'
+
contacts.length
+
'
contacts.');
};
function onError(contactError) {
alert('onError!');
};
// find all contacts with 'Bob' in any name field
var options = new ContactFindOptions();
options.filter="Bob";
var fields = ["displayName", "name"];
39
navigator.contacts.find(fields, onSuccess, onError,

navigator.contacts.find(fields, onSuccess, onError,

options);

navigator.contacts.find(fields, onSuccess, onError, options);

Contact

Contains properties that describe a contact, such as a user's personal or business contact.

Properties

id: A globally unique identifier. (DOMString)

displayName: The name of this Contact, suitable for display to end- users. (DOMString)

name: An object containing all components of a persons name. (ContactName)

nickname: A casual name to address the contact by. (DOMString)

phoneNumbers: An array of all the contact's phone numbers. (ContactField[])

emails: An array of all the contact's email addresses. (ContactField[])

addresses: An array of all the contact's addresses. (ContactAddresses[])

ims: An array of all the contact's IM addresses. (ContactField[])

organizations: An array of all the contact's organizations. (ContactOrganization[])

birthday: The birthday of the contact. (Date)

note: A note about the contact. (DOMString)

photos: An array of the contact's photos. (ContactField[])

categories: An array of all the contacts user defined categories. (ContactField[])

urls: An array of web pages associated to the contact. (ContactField[])

Methods

clone: Returns a new Contact object that is a deep copy of the calling object, with the id property set to null.

40

remove: Removes the contact from the device contacts database. An error callback is called with a ContactError object if the removal is unsuccessful.

save: Saves a new contact to the device contacts database, or updates an existing contact if a contact with the same id already exists.

Details

The Contact object represents a user contact. Contacts can be created, saved to, or removed from the device contacts database. Contacts can also be retrieved (individually or in bulk) from the database by invoking the contacts.find method.

Note: Not all of the above contact fields are supported on every device platform. Please check each platform's Quirks section for information about which fields are supported.

Supported Platforms

Android

BlackBerry WebWorks (OS 5.0 and higher)

iOS

Save Quick Example

function onSuccess(contact) {

alert("Save Success");

};
};

function onError(contactError) {

alert("Error = " + contactError.code);

};
};

// create a new contact object

var contact = navigator.contacts.create();

41

contact.displayName = "Plumber";

contact.nickname = "Plumber";

//specify both

to support all devices

 

// populate some fields

var name = new ContactName();

name.givenName = "Jane";

name.familyName = "Doe";

contact.name = name;

// save to device

contact.save(onSuccess,onError);

Clone Quick Example

// clone the contact object

var clone = contact.clone();

clone.name.givenName = "John";

console.log("Original contact name = " + contact.name.givenName); console.log("Cloned contact name =
console.log("Original
contact
name
=
"
+
contact.name.givenName);
console.log("Cloned
contact
name
=
"
+
clone.name.givenName);
Remove Quick Example
function onSuccess() {
alert("Removal Success");
};
function onError(contactError) {
alert("Error = " + contactError.code);
};
42

// remove the contact from the device

contact.remove(onSuccess,onError);

Android 2.X Quirks

categories: This property is not support by Android 2.X devices, and will always be returned as null.

Android 1.X Quirks

name: This property is not support by Android 1.X devices, and will always be returned as null.

nickname: This property is not support by Android 1.X devices, and will always be returned as null.

birthday: This property is not support by Android 1.X devices, and will always be returned as null.

photos: This property is not support by Android 1.X devices, and will always be returned as null.

categories: This property is not support by Android 1.X devices, and will always be returned as null.

urls: This property is not support by Android 1.X devices, and will always be returned as null.

BlackBerry WebWorks (OS 5.0 and higher) Quirks

id: Supported. Assigned by device when contact is saved.

displayName: Supported. Stored in BlackBerry user1 field.

nickname: This property is not supported, and will always be returned as null.

phoneNumbers: Partially supported. Phone numbers will be stored in BlackBerry fields homePhone1 and homePhone2 if type is 'home', workPhone1 and workPhone2 if type is 'work', mobilePhone if type is 'mobile', faxPhone if type is 'fax', pagerPhone if type is 'pager', and otherPhone if type is none of the above.

43

emails: Partially supported. The first three email addresses will be stored in the BlackBerry email1, email2, and email3 fields, respectively.

addresses: Partially supported. The first and second addresses will be stored in the BlackBerry homeAddress and workAddress fields, respectively.

ims: This property is not supported, and will always be returned as null.

organizations: Partially supported. The name and title of the first organization are stored in the BlackBerry company and title fields, respectively.

photos: - Partially supported. A single thumbnail-sized photo is supported. To set a contact's photo, pass in a either a Base64 encoded image, or a URL pointing to the image. The image will be scaled down before saving to the BlackBerry contacts database. The contact photo is returned as a Base64 encoded image.

categories: Partially supported. Only 'Business' and 'Personal' categories are supported.

urls: Partially supported. The first url is stored in BlackBerry webpage field.

iOS Quirks

displayName: This property is not supported by iOS and will be returned as null unless there is no ContactName specified. If there is no ContactName, then composite name, nickame or "" is returned for displayName, respectively.

birthday: For input, this property must be provided as a JavaScript Date object. It is returned as a JavaScript Date object.

photos: Returned Photo is stored in the application's temporary directory and a File URL to photo is returned. Contents of temporary folder is deleted when application exits.

categories: This property is not currently supported and will always be returned as null.

ContactAddress

Contains address properties for a Contact object.

44

Properties

pref: Set to true if this ContactAddress contains the user's preferred value. (boolean)

type: A string that tells you what type of field this is (example:

'home').

_(DOMString)

formatted: The full address formatted for display. (DOMString)

streetAddress: The full street address. (DOMString)

locality: The city or locality. (DOMString)

region: The state or region. (DOMString)

postalCode: The zip code or postal code. (DOMString)

country: The country name. (DOMString)

Details

The ContactAddress object stores the properties of a single address of a contact. A Contact object can have one or more addresses in a ContactAddress[] array.

Supported Platforms

Android

BlackBerry WebWorks (OS 5.0 and higher)

iOS

Quick Example

// display the address information for all contacts

function onSuccess(contacts) {

for (var i=0; i<contacts.length; i++) {

for

(var

j=0;

j<contacts[i].addresses.length; j++) {

 
 

alert("Pref:

"

+

contacts[i].addresses[j].pref + "\n" +

 
 

45

"Type:

"

+

contacts[i].addresses[j].type + "\n" +

 

"Formatted:

"

+

contacts[i].addresses[j].formatted + "\n" +

 

"Street

Address:

 

"

 

+

contacts[i].addresses[j].streetAddress + "\n" +

 

"Locality:

"

+

contacts[i].addresses[j].locality + "\n" +

 

"Region:

"

+

contacts[i].addresses[j].region + "\n" +

 

"Postal

Code:

 

"

+

contacts[i].addresses[j].postalCode + "\n" +

 

"Country:

"

+

contacts[i].addresses[j].country);

 
} } };
}
}
};

function onError(contactError) {

alert('onError!');

};
};

// find all contacts

var options = new ContactFindOptions();

options.filter="";

var filter = ["displayName","addresses"];

navigator.contacts.find(filter, onSuccess, onError,

navigator.contacts.find(filter, onSuccess, onError,

options);

navigator.contacts.find(filter, onSuccess, onError, options);

Android 2.X Quirks

46

pref: This property is not supported by Android 2.X devices and will always return false.

Android 1.X Quirks

pref: This property is not supported by Android 1.X devices and will always return false.

type: This property is not supported by Android 1.X devices and will always return null.

streetAddress: This property is not support by Android 1.X devices, and will always return null.

locality: This property is not support by Android 1.X devices, and will always return null.

region: This property is not support by Android 1.X devices, and will always return null.

postalCode: This property is not support by Android 1.X devices, and will always return null.

country: This property is not support by Android 1.X devices, and will always return null.

BlackBerry WebWorks (OS 5.0 and higher) Quirks

pref: This property is not supported on Blackberry devices and will always return false.

type: Partially supported. Only one each of "Work" and "Home" type addresses can be stored per contact.

formatted: Partially supported. Will return concatenation of all BlackBerry address fields.

streetAddress: Supported. Will return concatenation of BlackBerry address1 and address2 address fields.

locality: Supported. Stored in BlackBerry city address field.

region: Supported. Stored in BlackBerry stateProvince address field.

postalCode: Supported. Stored in BlackBerry zipPostal address field.

country: Supported.

47

iOS Quirks

pref: This property is not supported on iOS devices and will always return false.

formatted: Not currently supported.

ContactField

Supports generic fields in a Contact object. Some properties that are stored as ContactField objects include email addresses, phone numbers, and urls.

Properties

type: A string that tells you what type of field this is (example:

'home'). (DOMString)

value: The value of the field (such as a phone number or email address). (DOMString)

pref: Set to true if this ContactField contains the user's preferred value. (boolean)

Details

The ContactField object is a reusable component that is used to support contact fields in a generic fashion. Each ContactField object contains a value property, a type property, and a pref property. A Contact object stores several properties in ContactField[] arrays, such as phone numbers and email addresses.

In most instances, there are no pre-determined values for the type attribute of a ContactField object. For example, a phone number can have type values of 'home', 'work', 'mobile', 'iPhone', or any other value that is supported by the contact database on a particular device platform. However, in the case of the Contact photos field, PhoneGap makes use of the type field to indicate the format of the returned image. PhoneGap will return type: 'url' when the value attribute contains a URL to the photo image, or type: 'base64' when the returned value attribute contains a Base64 encoded image string.

Supported Platforms

48

Android

BlackBerry WebWorks (OS 5.0 and higher)

iOS

Quick Example

// create a new contact

var contact = navigator.contacts.create();

// store contact phone numbers in ContactField[]

var phoneNumbers = [3];

phoneNumbers[0] = new ContactField('work', '212-

phoneNumbers[0] = new ContactField('work', '212-

555-1234', false);

phoneNumbers[0] = new ContactField('work', '212- 555-1234', false);
phoneNumbers[1] = new ContactField('mobile', '917-

phoneNumbers[1] = new ContactField('mobile', '917-

555-5432', true); // preferred number

phoneNumbers[1] = new ContactField('mobile', '917- 555-5432', true); // preferred number
phoneNumbers[2] = new ContactField('home', '203-

phoneNumbers[2] = new ContactField('home', '203-

555-7890', false);

phoneNumbers[2] = new ContactField('home', '203- 555-7890', false);

contact.phoneNumbers = phoneNumbers;

// save the contact

contact.save();

Android Quirks

pref: This property is not support by Android devices, and will always return false.

BlackBerry WebWorks (OS 5.0 and higher) Quirks

type: Partially supported. Used for phone numbers.

value: Supported.

pref: This property is not supported, and will always return false.

49

iOS Quirks

pref: This property is not supported on iOS devices and will always return false.

ContactFindOptions

Contains properties that can be used to filter the results of a contacts.find operation.

Properties

filter: The search string used to find contacts. (DOMString) (Default: "")

multiple: Determines if the find operation should return multiple contacts. (Boolean) (Default: false)

Supported Platforms

Android

BlackBerry WebWorks (OS 5.0 and higher)

iOS

Quick Example

// success callback

function onSuccess(contacts) {

for (var i=0; i<contacts.length; i++) {

alert(contacts[i].displayName);

} };
}
};

// error callback

function onError(contactError) {

alert('onError!');

50

};
};

// specify contact search criteria

var options = new ContactFindOptions();

options.filter="";

 

// empty search string

returns all contacts

 

options.multiple=true;

// return multiple

results

 

filter

=

["displayName"];

//

return

contact.displayName field

 

// find contacts

navigator.contacts.find(filter, onSuccess, onError,

navigator.contacts.find(filter, onSuccess, onError,

options);

navigator.contacts.find(filter, onSuccess, onError, options);

ContactName

Contains name properties of a Contact object.

Properties

formatted: The complete name of the contact. (DOMString)

familyName: The contacts family name. (DOMString)

givenName: The contacts given name. (DOMString)

middleName: The contacts middle name. (DOMString)

honorificPrefix: The contacts prefix (example Mr. or Dr.) (DOMString)

honorificSuffix: The contacts suffix (example Esq.). (DOMString)

Details

The ContactName object stores name properties of a contact.

Supported Platforms

51

Android 2.X

BlackBerry WebWorks (OS 5.0 and higher)

iOS

Quick Example

function onSuccess(contacts) {

for (var i=0; i<contacts.length; i++) {

alert("Formatted:

"

+

contacts[i].name.formatted + "\n" +

 

"Family

Name:

"

+

contacts[i].name.familyName + "\n" +

 

"Given

Name:

"

+

contacts[i].name.givenName + "\n" +

 

"Middle

Name:

"

+

contacts[i].name.middleName + "\n" +

 

"Suffix:

"

+

contacts[i].name.honorificSuffix + "\n" +

 

"Prefix:

"

+

contacts[i].name.honorificSuffix);

 
} };
}
};

function onError(contactError) {

alert('onError!');

};
};

var options = new ContactFindOptions();

options.filter="";

filter = ["displayName","name"];

navigator.contacts.find(filter, onSuccess, onError,

navigator.contacts.find(filter, onSuccess, onError,

options);

navigator.contacts.find(filter, onSuccess, onError, options);

Android Quirks

52

formatted: Partially supported. Will return the concatenation of honorificPrefix, givenName, middleName, familyName and honorificSuffix but will not store.

BlackBerry WebWorks (OS 5.0 and higher) Quirks

formatted: Partially supported. Will return concatenation of BlackBerry firstName and lastName fields.

familyName: Supported. Stored in BlackBerry lastName field.

givenName: Supported. Stored in BlackBerry firstName field.

middleName: This property is not supported, and will always return null.

honorificPrefix: This property is not supported, and will always return null.

honorificSuffix: This property is not supported, and will always return null.

iOS Quirks

formatted: Partially supported. Will return iOS Composite Name but will not store.

ContactOrganization

Contains organization properties of a Contact object.

Properties

pref: Set to true if this ContactOrganization contains the user's preferred value. (boolean)

type: A string that tells you what type of field this is (example:

'home').

_(DOMString)

name: The name of the organization. (DOMString)

department: The department the contract works for. (DOMString)

title: The contacts title at the organization. (DOMString)

53

Details

The ContactOrganization object stores a contact's organization properties. A Contact object stores one or more ContactOrganization objects in an array.

Supported Platforms

Android

BlackBerry WebWorks (OS 5.0 and higher)

iOS

Quick Example

function onSuccess(contacts) {

for (var i=0; i<contacts.length; i++) {

for

(var

j=0;

j<contacts[i].organizations.length; j++) {

 

alert("Pref:

 

"

+

contacts[i].organizations[j].pref + "\n" +

 
 

"Type:

"

+

contacts[i].organizations[j].type + "\n" +

 
 

"Name:

"

+

contacts[i].organizations[j].name + "\n" +

 
 

"Department:

"

+

contacts[i].organizations[j].department + "\n" +

 
 

"Title:

"

+

contacts[i].organizations[j].title);

 
} } };
}
}
};

function onError(contactError) {

 

alert('onError!');

 
};
};

54

var options = new ContactFindOptions();

options.filter="";

filter = ["displayName","organizations"];

navigator.contacts.find(filter, onSuccess, onError,

navigator.contacts.find(filter, onSuccess, onError,

options);

navigator.contacts.find(filter, onSuccess, onError, options);

Android 2.X Quirks

pref: This property is not supported by Android 2.X devices and will always return false.

Android 1.X Quirks

pref: This property is not supported by Android 1.X devices and will always return false.

type: This property is not supported by Android 1.X devices and will always return null.

title: This property is not supported by Android 1.X devices, and will always be returned as null.

BlackBerry WebWorks (OS 5.0 and higher) Quirks

pref: This property is not supported by Blackberry devices and will always return false.

type: This property is not supported by Blackberry devices and will always return null.

name: Partially supported. The first organization name will be stored in the BlackBerry company field.

department: This property is not supported, and will always be returned as null.

title: Partially supported. The first organization title will be stored in the BlackBerry jobTitle field.

iOS Quirks

55

pref: This property is not supported on iOS devices and will always return false.

type: This property is not supported on iOS devices and will always return null.

name: Partially supported. The first organization name will be stored in the iOS kABPersonOrganizationProperty field.

department: Partially supported. The first department name will be stored in the iOS kABPersonDepartmentProperty field.

title: Partially supported. The first title will be stored in the iOS kABPersonJobTitleProperty field.

ContactError

A ContactError object is returned to the contactError callback when an error occurs.

Properties

code: One of the predefined error codes listed below.

Constants

ContactError.UNKNOWN_ERROR

ContactError.INVALID_ARGUMENT_ERROR

ContactError.TIMEOUT_ERROR

ContactError.PENDING_OPERATION_ERROR

ContactError.IO_ERROR

ContactError.NOT_SUPPORTED_ERROR

ContactError.PERMISSION_DENIED_ERROR

Description

The ContactError object is returned to the user through the contactError callback function when an error occurs.

contactSuccess

56

Success callback function that provides the Contact array resulting from a contacts.find operation.

function(contacts) {

// Do something

}
}

Parameters

contacts: The contact array resulting from a find operation. (Contact)

Example

function contactSuccess(contacts) {

for (var i=0; i<contacts.length; i++) {

console.log("Display

Name

=

"

+

contacts[i].displayName;

}
}

contactError

Error callback function for contact functions.

function(error) {

// Handle the error

}
}

contactFields

Required parameter of the contacts.find method. Use this parameter to specify which fields should be included in the Contact objects resulting from a find operation.

["name", "phoneNumbers", "emails"]

57

contactFindOptions

Optional parameter of the contacts.find method. Use this parameter to filter the contacts returned from the contacts database.

{
{

filter: "",

multiple: true,

};
};

Options

filter: The search string used to filter contacts. (DOMString) (Default: "")

multiple: Determines if the find operation should return multiple contacts. (Boolean) (Default: false)

G. Device

The device object describes the device's hardware and software.

Properties

device.name

device.phonegap

device.platform

device.uuid

device.version

Variable Scope

Since device is assigned to the window object, it is implicitly in the global scope.

58

// These reference the same `device`

//
//

var phoneName = window.device.name;

var phoneName = device.name;

device.name

Get the device's model name.

var string = device.name;

Description

device.name returns the name of the device's model or product. This value is set by the device manufacturer and may be different across versions of the same product.

Supported Platforms

Android

BlackBerry

BlackBerry WebWorks (OS 5.0 and higher)

iPhone

Quick Example

// Android:

Nexus One

returns "Passion"

(Nexus One code name)

 

//

Motorola Droid returns "voles"

// BlackBerry: Bold 8900

returns "8900"

// iPhone:

All devices

returns a name set

by iTunes e.g. "Joe's iPhone"

 
//
//

var name = device.name;

59

Android Quirks

Gets the product name instead of the model name.

The product name is often the code name given during production.

e.g. Nexus One returns "Passion", Motorola Droid returns "voles"

iPhone Quirks

Gets the device's custom name instead of the device model name.

The custom name is set by the owner in iTunes.

e.g. "Joe's iPhone"

device.phonegap

Get the version of phonegap running on the device.

var string = device.phonegap;

Description

device.phonegap returns the version of phonegap running on the device.

Supported Platforms

Android

BlackBerry

BlackBerry WebWorks (OS 5.0 and higher)

iPhone

Quick Example

var name = device.phonegap;

device.platform

60

Get the device's operating system name.

var string = device.platform;

Supported Platforms

Android

BlackBerry

BlackBerry WebWorks (OS 5.0 and higher)

iPhone

Quick Example

// Depending on the device, a few examples are:

//

- "Android"

 

//

- "BlackBerry"

//

- "iPhone"

 

//

- "webOS"

 
//
//

var devicePlatform = device.platform;

iPhone Quirks

All devices return iPhone as the platform. This is inaccurate because Apple has rebranded the iPhone operating system as iOS.

BlackBerry Quirks

Devices may return the device platform version instead of the platform name. For example, the Storm2 9550 would return '2.13.0.95' or similar.

device.uuid

Get the device's Universally Unique Identifier (UUID).

61

var string = device.uuid;

Description

The details of how a UUID is generated are determined by the device manufacturer and specific to the device's platform or model.

Supported Platforms

Android

BlackBerry

BlackBerry WebWorks (OS 5.0 and higher)

iPhone

Quick Example

// Android: Returns a random 64-bit integer (as a

// Android: Returns a random 64-bit integer (as a

string, again!)

// Android: Returns a random 64-bit integer (as a string, again!)

//

The integer is generated on the

device's first boot

 
//
//

// BlackBerry: Returns the PIN number of the device

//

This is a nine-digit unique integer

(as a string, though!)

 
//
//

//

iPhone: (Paraphrased from the UIDevice Class

documentation)

 

//

Returns a string of hash values created

from multiple hardware identifies.

 

//

It is guaranteed to be unique for every

device and cannot be tied

 

//

to the user account.

//
//

62

var deviceID = device.uuid;

device.version

Get the operating system version.

var string = device.version;

Supported Platforms

Android 2.1+

BlackBerry

BlackBerry WebWorks (OS 5.0 and higher)

iPhone

Quick Example

// Android:

Froyo OS would return "2.2"

 

//

Eclair OS would return "2.1",

"2.0.1", or "2.0"

 

//

Version can also return update level

"2.1-update1"

 
//
//
// BlackBerry: Bold 9000 using OS 4.6 would return

// BlackBerry: Bold 9000 using OS 4.6 would return

"4.6.0.282"

// BlackBerry: Bold 9000 using OS 4.6 would return "4.6.0.282"
//
//

// iPhone:

iOS 3.2 returns "3.2"

//
//

var deviceVersion = device.version;

63

H. Events

PhoneGap lifecycle events.

Event Types

backbutton

deviceready

menubutton

pause

resume

searchbutton

online

offline

backbutton

This is an event that fires when the user presses the back button on Android.

document.addEventListener("backbutton",

document.addEventListener("backbutton",

yourCallbackFunction, false);

document.addEventListener("backbutton", yourCallbackFunction, false);

Details

If you need to over ride the default back button behaviour on Android you can register and event listenter for the 'backbutton' event. It is no longer necessary to call any other method to over ride the back button behaviour. Now, you only need to register an event listener for 'backbutton'.

with

Typically,

document.addEventListener once you receive the PhoneGap 'deviceready'

event.

you

will

want

to

attach

an

event

listener

Supported Platforms

Android

64

Quick Example

document.addEventListener("backbutton",

document.addEventListener("backbutton",

onBackKeyDown, false);

document.addEventListener("backbutton", onBackKeyDown, false);

function onBackKeyDown() {

// Handle the back buton

}
}

deviceready

This is an event that fires when PhoneGap is fully loaded.

document.addEventListener("deviceready",

document.addEventListener("deviceready",

yourCallbackFunction, false);

document.addEventListener("deviceready", yourCallbackFunction, false);

Details

This is a very important event that every PhoneGap application should use.

PhoneGap consists of two code bases: native and JavaScript. While the native code is loading, a custom loading image is displayed. However, JavaScript is only loaded once the DOM loads. This means your web application could, potentially, call a PhoneGap JavaScript function before it is loaded.

The PhoneGap deviceready event fires once PhoneGap has fully loaded. After the device has fired, you can safely make calls to PhoneGap function.

with

Typically,

document.addEventListener once the HTML document's DOM has loaded.

you

will

want

to

attach

an

event

listener

Supported Platforms

Android

BlackBerry WebWorks (OS 5.0 and higher)

iPhone

Quick Example

65

document.addEventListener("deviceready",

document.addEventListener("deviceready",

onDeviceReady, false);

document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady() {

// Now safe to use the PhoneGap API

}
}

BlackBerry (OS 4.6) Quirks

Custom events are not supported in the RIM BrowserField (web browser view), so the deviceready event will never fire.

A workaround is to manually query PhoneGap.available until PhoneGap has fully loaded.

function onLoad() {

// BlackBerry OS 4 browser does not support events. // So, manually wait until PhoneGap
//
BlackBerry OS 4 browser
does
not support
events.
//
So,
manually
wait
until
PhoneGap
is
available.
//
var intervalID = window.setInterval(
function() {
if (PhoneGap.available) {
window.clearInterval(intervalID);
onDeviceReady();
}