Beginning PhoneGap Errata

miststizzaΚινητά – Ασύρματες Τεχνολογίες

10 Δεκ 2013 (πριν από 3 χρόνια και 10 μήνες)

89 εμφανίσεις

Beginning PhoneGap Errata

978
-
1118156650


The Beginning PhoneGap book was mostly written while PhoneGap 0.9.6 was the
current version. By the time the book was in review, we made alterations for the 1.0
release, but while the book was being printed, Nitobi

releases 1.1 and 1.2. Just recently,
PhoneGap released version 1.3, with further support for Windows Phone 7 and
BlackBerry development on the Mac.


Needless to say, there have been more than minor changes to the code and
approaches to development with P
honeGap. In some cases, functions/methods have
been deprecated, others have been added, and support for different mobile
devices/operating systems added or removed.


This document is a catalog of those changes as of January 2012.



Chapter 1

In October 201
1, Adobe acquired Nitobi, allowing the team to focus on contributing to
the PhoneGap framework. Adobe has expressed support for hosting the online
PhoneGap community and the PhoneGap Build service.


Furthermore, in October 2011, the PhoneGap code was init
ially contributed to the
Apache Software Foundation under the name “Apache Callback.” It will always remain
free and open source under the Apache License, Version 2.0.


Late in December, the PhoneGap developers decided to rename Apache Callback to
Apache C
ordova, and the transition will take place for the PhongeGap 1.4 release.



Chapter 2

Downloading PhoneGap for iOS (pp. 18
-
20)


When you run a new project, you’ll likely get an error now, because index.html was not
found. To fix this, copy the www folder
into your project in Xcode 4
--
not just the app’s
folder, but directly into Xcode 4.


When prompted, make sure to select
Create folder references for any added folders

and click Finish.




Downloading PhoneGap for Android (pp. 20
-
22)


At the end of step 10
: remove
import android.app.Activity;

line from the main Java
file.


After step 12:




Add
android:configChanges=“orientation|keyboardHidden”

to the activity tag in
AndroidManifest.




Add a second activity under application tag:

<activity android:name="com.
phonegap.DroidGap"
android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden">
<intent
-
filter> </intent
-
filter> </activity>



Downloading PhoneGap for Windows Phone (NEW MATERIAL)


Requirements: Windows 7 or Windows Vista with SP2.

You will also need to become an
App Hub member over at
http://create.msdn.com/en
-
US/home/membership


1.

Download and install the Windows Phone SDK at
http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=27570


2.

Download and install the latest copy of PhoneGap from
http://www.phonegap.com


3.

Once you downloa
d the PhoneGapStarter.zip file, copy it to your templates folder
located at
c:
\
Users
\
<username>
\
Documents
\
Visual Studio
2010
\
Templates
\
ProjectTemplates
\
Silverlight for Windows Phone


Chapter 4

A number of new events were introduced to PhoneGap post 1.0:




batterycritical



batterylow



batterystatus



startcallbutton



endcallbutton



volumedownbutton



volumeupbutton



batterycritical

This event fires when PhoneGap detects the battery has reached a critical level
threshold (value is device specific).


window.addEventL
istener(
"
batterycritical
"
,
batteryCriticalCallback, false);


The object has two properties:



level
: the percentage of battery (a number between 0 and 100)



isPlugged
: a boolean that represents whether or not the device is plugged in.


Use it this way:


windo
w.addEventListener("batterycritical", onBatteryCritical, false);


function onBatteryCritical(info) {





alert("Battery Level Critical " + info.level + "% Recharge
Soon!");

}



batterylow

This event fires when PhoneGap detects the battery has reached the
low battery
threshold (value is device specific).


window.addEventListener(
"
batterylow
"
, batteryLowCallback, false);


The object has two properties:



level
: the percentage of battery (a number between 0 and 100)



isPlugged
: a boolean that represents whether
or not the device is plugged in.


Use it this way:


window.addEventListener("batterylow", onBatteryLow, false);


function onBatteryLow(info) {





alert("Battery Level Low " + info.level + "%");

}



batterystatus

This event fires when PhoneGap detects a c
hange of at least 1 percentage point in
battery. It also fires when the device is plugged or unplugged.


window.addEventListener(
"
batterystatus
"
, batteryStatusCallback,
false);


The object has two properties:



level
: the percentage of battery (a number betw
een 0 and 100)



isPlugged
: a boolean that represents whether or not the device is plugged in.


Use it this way:


window.addEventListener("batterystatus", onBatteryStatus, false);


function onBatteryStatus(info) {





alert("Level: " + info.level + "%
\
n Plug
ged in? " +
info.isPlugged);

}


startcallbutton

This event fires when the user presses the start call button.
This is only supported for
BlackBerry WebWorks (OS 5.0+).


window.addEventListener(
"
startcallbutton
"
, onCallStart, false);


function onCallStart(
){


//handle the call start


//typically this is an override to default behavior

}



endcallbutton

This event fires when the user presses the end call button.
This is only supported for
BlackBerry WebWorks (OS 5.0+).


window.addEventListener(
"
endcallbutton
"
, onCallEnd, false);


function onCallEnd(){


//handle the call end


//typically this is an override to default behavior

}



volumedownbutton

This event fires when the user presses the volume down button.
This is only
supported for BlackBerry WebWorks (OS
5.0+).


window.addEventListener(
"
volumedownbutton
"
, onVolumeDown, false);


function onVolumeDown(){


//handle the volume down event


//typically this is an override to default behavior


//for example, you could take a photo with camera app

}




volumeupbut
ton

This event fires when the user presses the volume up button.
This is only supported
for BlackBerry WebWorks (OS 5.0+).


window.addEventListener(
"
volumeupbutton
"
, onVolumeUp, false);


function onVolumeUp(){


//handle the volume up event


//typically thi
s is an override to default behavior


//for example, you could take a photo with camera app

}



Chapter 5


Windows Phone 7 is now supported when using:




device.name



device.phonegap



device.platform



device.uuid



device.version


For device.version, Windows Ph
one 7 returns the current OS version number (for
example, Mango returns
7.10.7720
).



There is also now support for Windows Phone 7 when working with the Connection
object.


Notifications (beeps, alerts, confirmations) are also supported with Windows Phone

7.


On page 66, in the first example under the section
Using Alerts
, please ignore the line:


[AU: be sure to replace all tabs in your code with five spaces]


This line is an instruction left over from the editorial process and has no bearing on the
code
itself.


Chapter 7

The compass has two new features that should help you build compass apps:




compass.watchHeadingFilter



compass.clearWatchFilter


compass.watchHeadingFilter

The watchHeadingFilter will get the compass heading in degrees if it changes by a
t
least a certain number of degrees. For example, if you want to report a compass
heading if it changes by 5 degrees or more, you can now do that using this command.


var watchID = navigator.compass.watchHeadingFilter(onSuccess,
onError, myOptions);



The
compass measures the heading in degrees from 0 to 359.99. The
watchHeadingFilter command gets the device’s current heading when it changes by a
specified number of degrees. Each time the heading changes by the threshold, the
success callback function is ca
lled.


Only one filter can be in effect at any given time.
Use this function on iOS instead of
the compass.watchFilter() as it is more efficient.


NOTE: this new function is only supported on iOS devices.



For example:


function onSuccess(heading){


var m
yElement = document.getElementById(
'
myheading
'
);


myElement.innerHTML =
'
Your heading is
'

+
heading.magneticHeading;

}


function onError(error){


alert(
'
Compass error:
'
+ error.code);

}


//notify when compass heading changes by 5 degrees or more

var optio
ns = { filter: 5};


var watchID = navigator.compass.watchHeadingFilter(onSuccess,
onError, options);



In the example above, the watchHeadingFilter function is used to detect a change of 5
or more degrees. When this happens, the myheading DOM element text

is updated to
reflect the new heading.



compass.clearWatchFilter

Use this function to stop watching the compass referenced by a watch filter previously
set.


navigator.compass.clearWatchFilter(watchID);


where the watchID above is the ID returned by comp
ass.watchHeadingFilter.



NOTE: this new function is only supported on iOS devices.


For example:


//set a watchID

var options = { filter:20};

watchID =
navigator.compass.watchHeadingFilter(onSuccess,onError,options);


function onSuccess(heading){


//set y
our success parameters

}


function onError(error){


//handle error state

}


function stopWatching(){


if (watchID){



navigator.compass.clearWatchFilter(watchID);



watchID = null;


}

}



Chapter 9

There are a number of changes to the Media object.




A new

parameter called mediaStatus.



Two new methods: stopRecord and seekTo.



Two new readonly parameters: _position and _duration.


Furthermore, there is support for Windows Phone 7 now.


mediaStatus Parameter

The mediaStatus parameter is an optional callback fu
nction that is invoked to indicate
status changes.


var myMedia = new Media(src,onSuccess,onError,onStatus);


function onStatus(){


}



stopRecord Method

media.stopRecord is an asynchronous function that stops recording an audio file.


For example:


var sr
c =
"
myexample.mp3
"
;

var myRec = new Media (src,


function(){


console.log(“successfully recording!”);

},


function(error){


console.log(“error: “ + error.code);

});


myRec.startRecord();


function stopRecording(){


myRec.stopRecord();

}



seekTo Method

Th
e media.seekTo method sets the current position within an audio file.


media.seekTo(milliseconds);


The method has one parameter,
milliseconds
, which you can use to set the position on
playback. When you run seekTo, it updates the _position readonly parame
ter.


For example, if you want to jump to 15 seconds into a recording:


var myMedia = new Media(src,onSuccess,onError);

myMedia.play();

myMedia.seekTo(15000);



_position

The _position readonly parameter keeps track, in seconds, where you are in an audio
p
layback. Call getCurrentPosition to update.


_duration

The _duration readonly parameter contains the duration of the media in seconds.



Change to Example on page 122

Please note that the first example in the chapter is incorrect, as it divides the positio
n by
1000 to convert from milliseconds to seconds. This is no longer necessary.


Here’s the updated example:


<html>


<head>


<title>Media Example</title>



<script type="text/javascript" charset="utf
-
8"
src="phonegap.js"></script>



<script type="text/javascript" charset="utf
-
8">



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




function onDeviceReady() {


playAudio("
http://example.com/audio.mp3
"); /
/change
this


}



var myMedia = null;


var myTimer = null;



// Play audio


//


function playAudio(src) {


// Create Media object from src


myMedia = new Media(src, onSuccess, onError);




// Play audio


myMedia.play();



// Update my_media position every second


if (myTimer == null) {


myTimer = setInterval(function() {


// get my_media position


my
Media.getCurrentPosition(


// success callback


function(position) {


if (position >
-
1) {


setAudioPosition((position) + "
seconds");



}


},


// error callback


function(e) {


console.log("Error getting
position=" + e);


setAudioPosition("Error: " + e);



}


);


}, 1000);


}


}





function pauseAudio() {


if (myMedia) {


myMedia.pause();


}


}





function stopAudio() {



if (myMedia) {


myMedia.stop();


}


clearInterval(myTimer);


myTimer = null;


}





function onSuccess() {


console.log("Audio Success");


}





funct
ion onError(error) {


alert('code: ' + error.code + '
\
n' +


'message: ' + error.message + '
\
n');


}



function setAudioPosition(position) {


document.getElementById('position').innerHTML =
positio
n;


}



</script>


</head>


<body>


<a href="#"
onclick="playAudio('
http://example.com/audio.mp3'
);">


Play Audio</a>


<a href="#" onclick="pauseAudio();">Paus
e Playing
Audio</a>


<a href="#" onclick="stopAudio();">Stop Playing
Audio</a>


<p id="position"></p>


</body>


</html>



Chapter 10

Camera for Windows Phone 7 is now supported. Furthermore, they’ve added four new
parameters to the C
amera object:




EncodingType



targetWidth



targetHeight



MediaType


EncodingType

Use the EncodingType to choose the encoding of the returned image file. Set 0 for
JPEG or 1 for PNG:


Camera.EncodingType = { JPEG : 0, PNG: 1};


NOTE: EncodingType not supported
on Android.


targetWidth

Set the image width in pixels to scale it. Must be used with targetHeight. Aspect ratio is
maintained.


{ targetWidth: 100, targetHeight: 100 }


targetHeight

Set the image height in pixels to scale it. Must be used with targetWidth
. Aspect ratio is
maintained.


{ targetWidth: 100, targetHeight: 100 }



MediaType

Use to set the type of media to select from. Only works if PictureSourceType is
PHOTOLIBRARY or SAVEDPHOTOALBUM.


Camera.MediaType = { PICTURE: 0, VIDEO: 1, ALLMEDIA: 2};


P
ICTURE is the default mode and will take still pictures only. The VIDEO selection will
always return FILE_URI. The ALLMEDIA setting will allow you to select from photos and
videos.


NOTE: MediaType not supported on BlackBerry or Palm.



Chapter 13

The Con
tactFindOptions object, which is used to filter the results of a contacts.find
operation, has a new property:
multiple
.


The multiple property, which is set to false by default, can return multiple results if set to
true.


function onSuccess(contacts) {





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









document.write(contacts[i].name);





}

};


// error callback

function onError(contactError) {





alert('Ooops!');

};


// specify contact search criteria

var myOptions = new ContactFindOptions();

myOptio
ns.filter="";








// empty search string returns







// all contacts

myOptions.multiple=true;



// return multiple results

filter = ["name"];


// return contact.name field


// find contacts

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


Chapter 14

New support for Windows Phone 7 for the Capture API. There are also changes to
ConfigurationData and MediaFile.


ConfigurationData

The ConfigurationData object is new: it encapsulates a set of media capture parameters
supported by the device. Specifically:




the MIME types supported (video/3gpp, video/quicktime, image/jpeg, audio/wav, and
so on)



the height and width



an ASCII
-
encoded st
ring representing the media type


You can retrieve supported image modes like this:


var myImageModes = navigator.device.capture.supportedImageModes;


MediaFile and MediaFileData

The MediaFile object lets you set file name, path, MIME type, file size and o
ther
formatting data (codecs, bitrate, duration
--
all stored in MediaFileData) when working
with captured files.


Here are the properties:




name
: The name of the file, without path information



fullPath
: The full path to the file, including name.



type
: The M
IME type



lastModifiedDate
: The date and time that the file was last modified



size
: The size of the file in bytes


The MediaFileData object encapsulates the format information:



codecs:
actual format of the audio/video content



bitrate:
average bitrate of the

content



height:
height of image/video in pixels



width:
width of image/video in pixels



duration:
length of the video/audio file in seconds


By and large, if you’re developing on BlackBerry WebWorks or Android, you won’t be
able to use any of these MediaFil
eData. If you’re developing on iOS, codecs aren’t
supported, but height, width and duration are supported. Bitrate is only supported on
iOS4 devices, but only for audio.